PHP code example of evgsavosin / choco-router

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

    

evgsavosin / choco-router example snippets


composer 

 

declare(strict_types=1);

e ChocoRouter\HttpMethod;

$router = new SimpleRouter();

$router->addRoute(HttpMethod::GET, '/foo', fn (): string => 'Foo!' );
$router->addRoute(
    HttpMethod::POST, 
    '/foo/{bar}', 
    fn (mixed $value): string => "Foo bar and {$value}!",
    ['bar' => '[0-9]+']
);

try {
    $router->resolve(
        $_SERVER['REQUEST_METHOD'], 
        $_SERVER['REQUEST_URI']
    )->callableResolve(function (mixed $handler, array $arguments): mixed {
        if (is_string($handler)) {
            [$controllerName, $methodName] = explode('@', $handler);

            // PSR-11 implementation for classes: controllers, actions and etc...
        } elseif (is_callable($handler)) {
            $handler(...$arguments);
        }
    }); 
} catch (HttpException $e) {
    if ($e->getCode() === HttpException::NOT_FOUND) {
        // Handle 404...
    } else if ($e->getCode() === HttpException::BAD_REQUEST) {
        // Handle 400...
    }
}

$router->addRoute(HttpMethod::GET, '/foo/{bar?}', 'foo-bar', ['bar' => '[0-9]+']);

$router->addGroup('/gorge', function (RouteCollection $r): void {
    $router->addRoute(HttpMethod::GET, '/foo/{bar?}', 'foo-bar', ['bar' => '[0-9]+']);
});
 
HttpMethod::CONNECT
HttpMethod::HEAD
HttpMethod::GET
HttpMethod::POST
HttpMethod::PUT
HttpMethod::DELETE
HttpMethod::OPTIONS

$router = new SimpleRouter([
    'cacheDisable' => false,
    'cacheDriver' => FileDriver::class,
    'cacheOptions' => [] 

    /*
        For memcached driver, there passed array of servers. 
        For file driver, there passed path to cache directory.
    */
]);
 
use App\Action\FooAction;

$router = new SimpleRouter();
$router->load([FooAction::class]);
$router->resolve(/*...*/)->callableResolve(/*...*/);
 
$router = new SimpleRouter([
    'cacheDriver' => FileDriver::class
]);

$router->cache(static function (RouteCollection $r): void {
    $r->addRoute(HttpMethod::GET, '/foo/{bar}', App\Actions\FooAction::class, ['bar' => '[0-9]+']);
});

$router->resolve(/*...*/)->callableResolve(/*...*/);