PHP code example of crazy-goat / router

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

    

crazy-goat / router example snippets




ing = function (CrazyGoat\Router\RouteCollector $r) {
    $r->get('/users', 'get_all_users_handler');
    // {id} must be a number (\d+)
    $r->get('/user/{id:\d+}', 'get_user_handler');
    // The /{title} suffix is optional
    $r->get('/articles/{id:\d+}[/{title}]', 'get_article_handler');
};

$dispatcher = CrazyGoat\Router\DispatcherFactory::createFromClosure($routing);

// 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->getHandler();
    $params = $routeInfo->getVariables();
    $middlewareStack = $routeInfo->getMiddlewareStack();
    
    // ... call $handler with $vars
} catch (\CrazyGoat\Router\Exceptions\MethodNotAllowed $exception) {
    // ... 405 Method Not Allowed
} catch (\CrazyGoat\Router\Exceptions\RouteNotFound $exception) {
   // ... 404 Not Found
}

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

// 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');
    $r->addRoute(['GET'], '/do-something-else', 'handler');
});

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


$dispatcher = DispatcherFactory::createFileCached('data/router-file.php', 'cache/router.cache');


return function (CrazyGoat\Router\RouteCollector $r) {
    $r->get('/users', 'get_all_users_handler');
    // {id} must be a number (\d+)
    $r->get('/user/{id:\d+}', 'get_user_handler');
    // The /{title} suffix is optional
    $r->get('/articles/{id:\d+}[/{title}]', 'get_article_handler');
};


try {
    $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
    // ... your code 
} catch (\CrazyGoat\Router\Exceptions\MethodNotAllowed $exception) {
    $allowedMethods = $exception->getAllowedMethods();
}

$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
    
$handler = $routeInfo->getHandler();
$params = $routeInfo->getVariables();
$middlewareStack = $routeInfo->getMiddlewareStack();



namespace CrazyGoat\Router;

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

interface DataGenerator {
    public function addRoute(string $httpMethod, array $routeData, string $handler, array $middleware = [], ?string $name = null): void;
    public function getData(): array;
    public function hasNamedRoute(string $name): bool;
}

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

    public function dispatch(string $httpMethod, string $uri): RouteInfo;
    public function setData(array $data): void;
}



$config = new Configuration(
    new ClosureProvider($routingData),
    new RouteCollector(
        new CustomParser(),
        New CustomDataGenerator()
    ),
    new CustomDispatcher()       
);

$dispatcher = DispatcherFactory::createFromClosure(function(CrazyGoat\Router\RouteCollector $r) {
    $r->addRoute(['GET'], '/users', 'get_all_users_handler', ['root_middleware']);
    $r->addGroup('/nested', function (CrazyGoat\Router\RouteCollector $r) {
        $r->addRoute(['GET'], '/users', 'handler3', ['nested-middleware']);
    }, ['group_middleware']);
});

    $r->addRoute(['GET'], '/users', 'get_all_users_handler', ['first', 'second']);

$r->addRoute(['GET'], '/users', 'get_all_users_handler', ['first', 'second']);

//some usefull code

$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
$middlewares = $routeInfo->getMiddlewareStack();

$r->addRoute(['GET'], '/users', 'get_all_users_handler', [], 'users');

// some crazy code

$path = $dispatcher->produce('users', $route_params);