PHP code example of phossa / phossa-route

1. Go to this page and download the library: Download phossa/phossa-route library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phossa / phossa-route example snippets


  use Phossa\Route\Dispatcher;

  // dispatcher with default collector & resolver
  $dispatcher = (new Dispatcher())
      ->addGet(
          '/blog/{action:xd}[/{year:d}[/{month:d}[/{date:d}]]]',
          function($result) {
              echo "action is " . $result->getParameter('action');
          })
      ->addPost('/blog/post', 'handler2')
      ->addRoute(new Route\Route(
          'GET,HEAD', // multiple methods
          '/blog/read[/{id:d}]',
          'handler3',
          ['id' => '1'])); // default $id value

  // route base on info provided by server
  $dispatcher->dispatch();
  

  use Phossa\Route\Dispatcher;

  /*
   * routes.php :
   * return [
   *     '/user/phossa'  => 'handler1',
   *     '/user/{action:xd}/{id:d}'   => [['controller', 'action'], 'GET,POST'],
   *     '/user/view[/{id:d}]' => ['handler2', 'GET', ['id' => 23]]
   * ];
   */
  $dispatcher = (new Dispatcher())->loadRoute('./routes.php');
  

  // with 'action' & 'id' two named params
  $dispatcher->addGet('/user/{action:[^0-9/][^/]*}/{id:[0-9]+}', 'handler1');
  

  ':d}'   => ':[0-9]++}',             // digit only
  ':l}'   => ':[a-z]++}',             // lower case
  ':u}'   => ':[A-Z]++}',             // upper case
  ':a}'   => ':[0-9a-zA-Z]++}',       // alphanumeric
  ':c}'   => ':[0-9a-zA-Z+_\-\.]++}', // common chars
  ':nd}'  => ':[^0-9/]++}',           // not digits
  ':xd}'  => ':[^0-9/][^/]*+}',       // no leading digits
  

  // with 'action' & 'id' two named params
  $dispatcher->addGet('/user/{action:xd}/{id:d}', 'handler1');
  

  // $action, $year/$month/$date are all optional
  $pattern = '/blog[/{action:xd}][/{year:d}[/{month:d}[/{date:d}]]]';
  

  // $action, $year/$month/$date are all optional
  $pattern = '/blog[/{action:xd=list}][/{year:d=2016}[/{month:d=01}[/{date:d=01}]]]';
  

  $dispatcher = (new Dispatcher())->addPost('/blog/post', 'handler2');
  

  // '/user' related
  $collector_user = (new Route\Collector\Collector())
      ->addGet('/user/list/{id:d}', 'handler1')
      ->addGet('/user/view/{id:d}', 'handler2')
      ->addPost('/user/new', 'handler3');

  // '/blog' related
  $collector_blog = (new Route\Collector\Collector())
      ->addGet('/blog/list/{user_id:d}', 'handler4')
      ->addGet('/blog/read/{blog_id:d}', 'handler5');

  $dispatcher->addCollector($collector_user)
             ->addCollector($collector_blog);
  

  $dispatcher
      ->addGet('/user/{$id}', 'handler1')
      ->addPost('/user/{$id}', 'handler2');
  

  // index.php
  // ...

  // dispatch base on server request info
  $dispatcher->dispatch();
  

  $dispatcher->dispatchUrl('GET', '/error404');
  

  // use info from $_SERVER etc.
  if ($dispatcher->match()) {
      $result = $dispatcher->getResult();
      switch($result->getStatus()) {
          case 200:
            // ...
            break;
          case 404:
            // ...
            break;
          default:
            // ...
            break;
      }
  } else {
      // no match found
      // ...
  }
  

  use Phossa\Route\Route;
  use Phossa\Route\Status;

  $route = (new Route('GET', '/user/{action:xd}/{id:d}',
      function($result) { // handler for Status::OK
          $user_id = $result->getParameter('id');
          // ...
      })->addHandler(Status::METHOD_NOT_ALLOWED, 'handler1'); // extra handler
  

  use Phossa\Route\Status;

  $dispatcher->addHandler(
      Status::SERVICE_UNAVAILABLE,
      function($result) {
          // ...
      }
  );
  

  $collector->addHandler(
      Status::MOVED_PERMANENTLY,
      function($result) {
          // ...
      }
  );
  

  use Phossa\Route;

  // dispatcher with default resolver
  $dispatcher = new Route\Dispatcher(
      new Route\Collector\Collector(),
      new Route\Handler\ResolverAbstract()
  );
  

  use Phossa\Route\Dispatcher
  use Phossa\Route\Extensions\RedirectToHttpsExtension;

  // create dispatcher
  $dispatcher = new Dispatcher();

  // direct any HTTP request to HTTPS port before any routing
  dispatcher->addExtension(new RedirectToHttpsExtension());
  

  $dispatcher->addExtension(
      function($result) {
          $pattern = $result->getRequest()->getPattern();
          if ('/user' == substr($pattern, 0, 5) && !isset($_SESSION['auth'])) {
              $result->setStatus(Status::UNAUTHORIZED);
              return false; // return to dispatcher level
          }
          return true; // authed or not in /user
      },
      Dispatcher::BEFORE_MATCH // run this extension before matching
  );

  // set default auth handler at dispatcher level
  $dispatcher->addHandler(
      Status::UNAUTHORIZED,
      function($result) {
          // display auth page etc.
      }
  );
  

  $route->addExtension(
      function($result) {
          $id = (int) $result->getParameter('id');
          if ($id > 1000) { // not allowed
              $result->setStatus(Status::PRECONDITION_FAILED);
              return false;
          }
          return true;
      },
      Route::BEFORE_ROUTE // before execute route handler
  );
  

  $collector->addExtension(
      function($result) {
          // collect statistics
      },
      Collector::BEFORE_COLL // before collector match
  )->addExtension(
      function($result) {
          // collect statistics
      },
      Collector::AFTER_COLL // after a successful match
  );
  

  // match against $_SERVER, $_REQUEST, $_SESSION, $_COOKIE etc.
  $route = (new Route('GET', '/user/list/{$id}', 'handler1'))
      ->addFilter('server.server_name', '(m|www).phossa.com')
      ->addFilter('cookie.vote_status', 'voted');
  

  // closure takes the value from $_SERVER['SERVER_NAME'] as input
  $route->addFilter('server.server_name', function($value) {
      switch($value) {
        case 'a1.phossa.com':
        case 'b2.phossa.com':
            return true;
        default:
            return false; // always return a bool
      }
  });
  

  $dispatcher->setDebugMode(true)->setDebugger($logger);
  

  // created with default RER collector
  $dispatcher = new Dispatcher();

  // add supprot for legacy query parameter routing
  $dispatcher->addCollector(new CollectorQPR());
  

  use Phossa\Route\Dispatcher;
  use Phossa\Route\Regex\ParserStd;
  use Phossa\Route\Collector\Collector;

  // use standard algorithm
  $dispatcher = new Dispatcher(new Collector(new ParserStd));
  

    DirectorySlash Off
    Options -MultiViews
    DirectoryIndex index.php
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^ index.php [QSA,L]
    

    server {
        listen       80;
        server_name  www.mysite.com mysite.com;
        root         /path/www.mysite.com/public;

        try_files $uri $uri/ /index.php$is_args$args;

        location /index.php {
            fastcgi_connect_timeout 3s;
            fastcgi_read_timeout 10s;