phproutes

Why do I need PHP routers?


background

last month I designed my first REST API as my effort to learn php, it was a chat messenger, to provide access to different APIs I relied on the folder and file structure, i.e. the URL was pointing to a actual file in server path and that file was a complete script to do it's job, so all that the app using API had to do was to call the specific URL and provide proper input,

Question

Lately, I read about Routers, and this question came to my mind, Why should I use routers and do I really need them?
my points so far:
_Without using Routers the API design and access is easy, the Apache handles the routing(If I am not wrong).
_With routers code is more complex however I can have some code running without the actual script being engaged, so I have more control over API access and such.


Solution

  • While Yassine has pointed out an answer elsewhere which contains a lot of information, it is a bit misleading (and wrong) in some regards.

    A router is commonly used as part of a front controller architecture pattern. This funnels all incoming requests to a specific handler which will normally then pass the request on to a specific bit of functionality via the router.

    The advantage of doing this is that it avoids duplication of code - specifically to handle things like session management, authentication, authorization, and templating.

    Consider, for example:

     <?php
     /* this script implements a front controller */
     $sitedown=$_SERVER['DOCUMENT_ROOT'] . "/sitedown.php";
     if (file_exists($sitedown)) {
        require_once($sitedown);
        exit;
     }
     require_once("session/use_memcache_sessions.inc");
     require_once("session/authorization.inc");
     require_once("router.inc");
     require_once("template/pagelayout.inc");     
    
     session_start();
     begin_page_template($_SESSION['user_prefs']);
    
     if (is_authorized($_SERVER['PHP_SELF'], $_SESSION['user_groups'])) {
         /* now the script invokes the router.... */
         route_request($_SERVER['PHP_SELF']);
     } else {
         show_unauth_message();
     }
     
     end_page_template();
    

    While you could just drop lots of self-contained scripts onto your filesystem, with each one acting as an entry point, each of them would need to implement the logic above. If you decided to start using redis for your session management, or change the templating, you would need to change each script to accomodate the new behaviour.