PHP code example of phossa2 / route

1. Go to this page and download the library: Download phossa2/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/ */

    

phossa2 / route example snippets


use Phossa2\Route\Route;
use Phossa2\Route\Dispatcher;

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

// diaptcher (match & execute controller action)
$dispatcher->dispatch('GET', '/blog/list/2016/05/01');

$routes = [
    '/user/{action:xd}/{id:d}' => [
        'GET,POST',               // methods,
        function ($result) {
            $params = $result->getParameters();
            echo "user id is " . $params['id'];
        },                        // handler,
        ['id' => 1]               // default values
    ],
    // ...
];
$dispatcher = (new Dispatcher())->loadRoutes($routes);
$dispatcher->dispatch('GET', '/user/view/123456');

  // 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->addGet($pattern, function($result) {
      $params = $result->getParameters();
      echo $params['year'];
  })->dispatch('GET', '/blog');
  

  // a new route collector will be added automatically if not yet
  $dispatcher = (new Dispatcher())->addPost('/blog/post', 'handler2');
  

  use Phossa2\Route\Collector\Collector;

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

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

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

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

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

  $dispatcher->dispatch('GET', '/user/view/123');
  

  if ($dispatcher->match('GET', '/user/view/1234')) {
      $result = $dispatcher->getResult();
      switch($result->getStatus()) {
          case 200:
            // ...
            break;
          case 404:
            // ...
            break;
          default:
            // ...
            break;
      }
  } else {
      // no match found
      // ...
  }
  

  use Phossa2\Route\Route;
  use Phossa2\Route\Status;

  $route = new Route(
      'GET',
      '/user/{action:xd}/{id:d}',
      function($result) { // handler for Status::OK
          // ...
      }
  );
  

  use Phossa2\Route\Status;

  $dispatcher->addHandler(
      function($result) {
          echo "method " . $result->getMethod() . " not allowed";
      },
      Status::METHOD_NOT_ALLOWED
  );
  

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

  use Phossa2\Route\Status;

  $dispatcher->addHandler(
      function($result) {
          echo "no other handler found";
      },
      0 // <-- match all other status
  );
  

  use Phossa2\Route\Collector\Collector;
  use Phossa2\Route\Resolver\ResolverSimple;

  // dispatcher with default resolver
  $dispatcher = new Route\Dispatcher(
      new Collector(),
      new ResolverSimple() // the default resolver anyway
  );
  

  use Phossa2\Route\Status;
  use Phossa2\Route\Dispatcher;
  use Phossa2\Route\Extensions\RedirectToHttps;

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

  // direct any HTTP request to HTTPS port before any routing
  $dispatcher
      ->addExtension(new RedirectToHttps())
      ->addHandler(function() {
            echo "redirect to https";
        }, Status::MOVED_PERMANENTLY)
      ->dispatch('GET', '/user/view/123');
  

  use Phossa2\Route\Status;
  use Phossa2\Route\Dispatcher;
  use Phossa2\Route\Extensions\UserAuth;

  $dispatcher = new Dispatcher();

  $dispatcher
    // add handler for unauthorized routing
    ->addHandler(
        function() {
            echo "need auth";
        }, Status::UNAUTHORIZED)

    // add a route
    ->addGet('/user/view/{id:d}', function() {
            echo "AUTHED!";
        })

    // add extension to force auth routes under '/user/'
    ->addExt(function($event) {
            $result = $event->getParam('result');
            $path = $result->getPath();
            if (!isset($_SESSION['authed']) && '/user/' === substr($path, 0, 6)) {
                $result->setStatus(Status::UNAUTHORIZED);
                return false;
            }
            return true;
        }, Dispatcher::EVENT_BEFORE_MATCH);

  // try a not authed route
  $dispatcher->dispatch('GET', '/user/view/123');

  // try a authed route
  $_SESSION['authed'] = 1;
  $dispatcher->dispatch('GET', '/user/view/123');
  

  use Phossa2\Route\Status;
  use Phossa2\Route\Dispatcher;
  use Phossa2\Route\Extensions\IdValidation;

  $dispatcher = new Dispatcher();

  // add extension to a route
  $route = (new Route('GET', '/user/{id:d}', null))
    ->addExtension(new IdValidation());

  // will fail
  $dispatcher->addRoute($route)->dispatch('GET', '/user/1000');
  

$dispatcher->enableDebug()->setDebugger($logger);

  // created with default RER collector
  $dispatcher = (new Dispatcher())
      ->addCollector(new Collector())     // regex based routing first
      ->addCollector(new CollectorQPR()); // support for legacy QPR
  

  use Phossa2\Route\Dispatcher;
  use Phossa2\Route\Parser\ParserStd;
  use Phossa2\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;