PHP code example of andrewcarteruk / simple-route

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

    

andrewcarteruk / simple-route example snippets


use SimpleRoute\Route;
use SimpleRoute\Router;

$router = Router::fromArray([
    new Route('GET', '/', 'handler1'),
    new Route('GET', '/{page}', 'handler2'),
]);

try {
    $result = $router->match($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);

    $handler = $result->getHandler();
    $params = $result->getParams();

    // ...
} catch (SimpleRoute\Exception\NotFoundException $exception) {
    // ...
} catch (SimpleRoute\Exception\MethodNotAllowedException $exception) {
    // ...
}

$route = new Route($method, $pattern, $handler);

$routes = [
    // This route
    new Route(['GET', 'POST'], '/test', 'handler'),

    // Is equivalent to these two routes together
    new Route('GET', '/test', 'handler'),
    new Route('POST', '/test', 'handler'),
];

$routes = [
    // Matches /user/42, but not /user/xyz
    new Route('GET', '/user/{id:\d+}', 'handler'),

    // Matches /user/foobar, but not /user/foo/bar
    new Route('GET', '/user/{name}', 'handler'),

    // Matches /user/foo/bar as well
    new Route('GET', '/user/{name:.+}', 'handler'),
];

$routes = [
    // This route
    new Route('GET', '/user/{id:\d+}[/{name}]', 'handler'),

    // Is equivalent to these two routes together
    new Route('GET', '/user/{id:\d+}', 'handler'),
    new Route('GET', '/user/{id:\d+}/{name}', 'handler'),

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