Home php How to organize Router PHP

How to organize Router PHP

Author

Date

Category

Tell me the algorithm, stages, how best to make such a routing system. I read a lot about routing but, there everything was somehow implemented, without registering them. I tried to disassemble the Framework-and, but everything is somehow difficult.

Tell me where to start, or advise a similar ready-made system.

p.s. Please do not scold the future for your bike. 🙂

Router settings are recorded as follows:

& lt;? php
  Return Array (
  'home' = & gt; Array (
    'Pattern' = & gt; '/'
    'Controller' = & gt; 'Blog \\ controller \\ indexcontroller',
    'action' = & gt; 'index'
  ),
  'Hello' = & gt; Array (
   'Pattern' = & gt; '/'
   'Controller' = & gt; 'Blog \\ Controller \\ Hellocontroller',
   'action' = & gt; 'index'
  ),
  'show_post' = & gt; Array (
   'Pattern' = & gt; '/ posts / {id}',
   'Controller' = & gt; 'Blog \\ controller \\ postcontroller',
   'action' = & gt; 'Show',
   '_requirements' = & gt; Array (
    'id' = & gt; '\ d +'
   )
  ),
 );
 Class Router {
  Private $ Registry;
  Private $ Path;
  Private $ args = array ();
  FUNCTION __CONSTRUCT ($ registry) {// List of all routers
   $ this- & gt; registry = $ registry;
  }
}

Answer 1, Authority 100%

You need to use SPL_AUTOLOAD_REGISTER .
Simply put, autoloading classes.
It should look like this: so:
SPL_AUTOLOADER_REGISTER (“AUTOLOADER”);

function autoloader ($ class) {
$ dirs = array (
'Controllers /',
'models /',
'core /'
);
$ Class = Strtolower ($ Class);
Foreach ($ Dirs AS $ Location) {
If (File_exists (__ dir __. '/' $ Location. $ class. 'PHP')) {
Require_ONCE (__ dir __. '/' $ Location. $ Class. '. PHP');
Break;
}
}
}

And then, through Route, do checks ..


Answer 2

I wrote my bike and solved this task in my own using regular expressions as a rules:
1) Create rules and drive them into a global variable:

$ globals ['routing'] = array (
  '' = & gt; Array (
    'Controller' = & gt; 'Cwelcome',
    'action' = & gt; 'index'
  ),
  'login' = & gt; Array (
    'Controller' = & gt; 'Cwelcome',
    'action' = & gt; 'Login'
  ),
  'logout' = & gt; Array (
    'Controller' = & gt; 'Cwelcome',
    'action' = & gt; 'logout'
  ),
  'admin $' = & gt; Array (
    'Controller' = & gt; 'Cadmin',
    'action' = & gt; 'index',
    'Roles' = & gt; Array ('A')
  ),
  'Admin / Users $' = & gt; Array (
    'Controller' = & gt; 'Cusers',
    'action' = & gt; 'index',
    'Roles' = & gt; Array ('A')
  ),
  'Admin / Users / | [\ d] +' = & gt; Array (
    'Controller' = & gt; 'Cusers',
    'action' = & gt; 'edit',
    'Roles' = & gt; Array ('A')
  ),
  'Products $' = & gt; Array (
    'Controller' = & gt; 'Cproducts',
    'action' = & gt; 'index',
    'db' = & gt; Table_Products.
  ),
  'Products / | [\ w] +' = & gt; Array (
    'Controller' = & gt; 'Cproducts',
    'action' = & gt; 'Single_Product',
    'db' = & gt; Table_Products.
  )
);

Rules are written according to the syntax of regular expressions except the slash ‘/’ (I correctly correct in the line of the router line $ TMP = STR_REPLACE (‘/’, ‘/’, $ Key); ) for greater readability and lightness of filling, and added the conventional separator symbol ‘|’ To separate from the function of the controller of additional parameters, for example http://site.com/admin/users/11– 11 Here youth ID, admin controller, users – function. You can go further and transmit an unlimited number of parameters, but this is according to the application logic. If the Integer 11 gives it to the line – we get 404.

2) Next, I created the Router class which calls in index.php as New Router ($ _ server [‘script_url’]); – Naturally, I have already connected controllers . And here is the Router class code itself:

class Router { 
Public Function __Construct ($ Request_uri)
  {
    global $ routing;
    $ Request_uri = Trim ($ Request_uri, '/');
    $ classname = '';
    $ ActionName = '';
    $ ROUTE_DATA = Array ();
    // ***
    $ Matches = Array ();
    $ args = array ();
    Foreach ($ Routing AS $ Key = & GT; $ Values)
    {
      $ TMP = STR_REPLACE ('/', '\', $ Key);
      $ TMP = STR_REPLACE ('|', '', $ TMP);
      //http://php.net/manual/ru/function.preg-match-all.php.
      if (preg_match_all ('/'. $ TMP. '/', $ Request_uri, $ Matches, Preg_Set_Order) === 1)
      {
        $ ROUTE_DATA = $ Values;
        $ classname = $ route_data ['Controller'];
        $ ActionName = $ ROUTE_DATA ['Action'];
        $ TMP = Explode ('|', $ Key);
        if (ISset ($ TMP [1]))
        {
          $ TMP = STR_REPLACE ($ TMP [0], '', $ Request_uri);
          $ TMP = TRIM ($ TMP, '/');
          if (! Empty ($ TMP))
          {
            $ Args = Explode ('/', $ TMP);
          }
        }
        Break;
      }
    }
    If (! Empty ($ classname) and! empty ($ actionName))
    {
      If (ISSET ($ ROUTE_DATA ['Roles']) and! Empty ($ ROUTE_DATA ['Roles']))
      {
        $ ERR_MESSAGE = 'You Have Not Access Permissions or Your Session Expired!'
        $ user_model = new musers ();
        if ($ user_model- & gt; is_user_logged_in ())
        {
          $ user_data = $ user_model- & gt; get_current_user ();
          if ($ user_data)
          {
            if (! In_Array ($ User_Data ['Role'], $ ROUTE_DATA ['Roles']))
            {
              DIE ($ ERR_MESSAGE);
            }
          } ELSE.
          {
            DIE ($ ERR_MESSAGE);
          }
        } ELSE.
        {
          DIE ($ ERR_MESSAGE);
        }
      }
    }
    // +++
    If (Class_exists ($ ClassName))
    {
      $ o = new $ classname ();
      $ O- & GT; {$ ActionName} ($ Args);
    } ELSE.
    {
      // Printf ('Class% s doesn exists!', $ classname);
      echo render_html ('Front / 404');
    }
  }
}

musers – user class – model – in which the logging and role of the user, and if the role is not included in Roles rules indicated in the $ routing array, the user will receive a refusal to issue a page

render_html – HTML generation function via the view:

function render_html ($ pagepath, $ data = array ())
{
  $ pagepath = STR_REPLACE (Array ('/', '\\'), Directory_Separator, $ PAGPATH);
  If (IS_Array ($ Data))
  {
    @extract ($ DATA);
  }
  OB_START ();
  Include (Abspath. 'Templates /'. $ PAGPATH. '.PHP');
  RETURN OB_GET_CLEAN ();
}

I described it in the Helper file, at this stage there was no need to create a class for 1 this function so I do not write a CMS or that it seems that it is all under the project, no extra codes and wrappers. Connect controllers is also better in routing, it has not yet done, since if they are 50 pieces, but only one thing is needed to connect a bunch of 49 unnecessary controllers.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions