PHP code example of pedrofaria / router

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

    

pedrofaria / router example snippets




atcher = Router\simpleDispatcher(function(Router\RouteCollector $r) {
    $r->addRoute('GET', '/users', 'get_all_users_handler');
    // {id} must be a number (\d+)
    $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler');
    // The /{title} suffix is optional
    $r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler');
    // Pass extra data for check ahead.
    $r->addRoute('DELETE', '/user/{id:\d+}', ['auth']);
});

// Fetch method and URI from somewhere
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];

// Strip query string (?foo=bar) and decode URI
if (false !== $pos = strpos($uri, '?')) {
    $uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);

try {
    $routeInfo = $dispatcher->dispatch($httpMethod, $uri);

    $handler = $routeInfo->handler;
    $vars = $routeInfo->variables;

    if (in_array('auth', $routeInfo->data)) {
        // Check if current user is authenticated before continue
    }
    
    // ... call $handler with $vars
} catch (\Router\Exception\HttpNotFoundException $e) {
    // ... 404 Not Found
} catch (\Router\Exception\HttpMethodNotAllowedException $e) {
    // ... 405 Method Not Allowed
}

$r->addRoute($method, $routePattern, $handler, $data = []);

// These two calls
$r->addRoute('GET', '/test', 'handler');
$r->addRoute('POST', '/test', 'handler');
// Are equivalent to this one call
$r->addRoute(['GET', 'POST'], '/test', 'handler');

// Matches /user/42, but not /user/xyz
$r->addRoute('GET', '/user/{id:\d+}', 'handler');

// Matches /user/foobar, but not /user/foo/bar
$r->addRoute('GET', '/user/{name}', 'handler');

// Matches /user/foo/bar as well
$r->addRoute('GET', '/user/{name:.+}', 'handler');

// This route
$r->addRoute('GET', '/user/{id:\d+}[/{name}]', 'handler');
// Is equivalent to these two routes
$r->addRoute('GET', '/user/{id:\d+}', 'handler');
$r->addRoute('GET', '/user/{id:\d+}/{name}', 'handler');

// Multiple nested optional parts are possible as well
$r->addRoute('GET', '/user[/{id:\d+}[/{name}]]', 'handler');

// This route is NOT valid, because optional parts can only occur at the end
$r->addRoute('GET', '/user[/{id:\d+}]/{name}', 'handler');

$r->get('/get-route', 'get_handler');
$r->post('/post-route', 'post_handler');

$r->addRoute('GET', '/get-route', 'get_handler');
$r->addRoute('POST', '/post-route', 'post_handler');

$r->addGroup('/admin', function (RouteCollector $r) {
    $r->addRoute('GET', '/do-something', 'handler');
    $r->addRoute('GET', '/do-another-thing', 'handler', ['other-data']);
    $r->addRoute('GET', '/do-something-else', 'handler');
}, ['extra_data']);

$r->addRoute('GET', '/admin/do-something', 'handler', ['extra_data']);
$r->addRoute('GET', '/admin/do-another-thing', 'handler', ['extra_data', 'other-data']);
$r->addRoute('GET', '/admin/do-something-else', 'handler', ['extra_data']);
 



$dispatcher = Router\cachedDispatcher(function(Router\RouteCollector $r) {
    $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0');
    $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1');
    $r->addRoute('GET', '/user/{name}', 'handler2');
}, [
    'cacheFile' => __DIR__ . '/route.cache', /* 

//...
catch (Router\Exception\HttpMethodNotAllowedException $e) {
    $allowedMethods = $e->getAllowedMethod();
}

/* Routing against GET /user/nikic/42 */

object(Router\Route)#7 (5) {
  ["httpMethod"]=>
  string(3) "GET"
  ["regex"]=>
  string(21) "/user/([^/]+)/([^/]+)"
  ["variables"]=>
  array(2) {
    ["name"]=>
    string(5) "nikic"
    ["id"]=>
    string(2) "42"
  }
  ["handler"]=>
  string(8) "handler0"
  ["data"]=>
  array(0) {
  }
}



namespace Router;

interface RouteParser {
    public function parse($route);
}

interface DataGenerator {
    public function addRoute($httpMethod, $routeData, $handler, array $data = []);
    public function getData();
}

interface Dispatcher {
    const NOT_FOUND = 0, FOUND = 1, METHOD_NOT_ALLOWED = 2;

    public function dispatch($httpMethod, $uri);
}



$dispatcher = Router\simpleDispatcher(function(Router\RouteCollector $r) {
    /* ... */
}, [
    'routeParser' => 'Router\\RouteParser\\Std',
    'dataGenerator' => 'Router\\DataGenerator\\GroupCountBased',
    'dispatcher' => 'Router\\Dispatcher\\GroupCountBased',
]);