PHP code example of hulotte / routing

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

    

hulotte / routing example snippets


$dispatcher = new \Hulotte\Routing\RouteDispatcher();

$dispatcher->addRoute('/accueil', 'accueil', function(){
    return 'Hello World';
});

$dispatcher->addRoute('/accueil', 'accueil', function(){
    return 'Hello World';
}, 'POST');

$dispatcher->addRoute('/accueil', 'accueil', function(){
    return 'Hello World';
}, ['GET', 'POST']);

$dispatcher->addRoute('/accueil', 'accueil', function(){
        return 'Hello World';
    })
    ->addRoute('/blog', 'blog', function(){
        return 'Welcome on my blog';
    });

$dispatcher->addRoute('/article/{id:\d+}/{slug:[a-z-]*}', 'accueil', function(ServerRequestInterface $request){
    $params = $request->getAttributes();
});

// $request is an object that implements ServerRequestInterface
// Response is an object that implements ResponseInterface

$route = $dispatcher->match($request);

if ($route === null) {
    return new Response(404, [], 'Not found !');
}

$callable = $route->getCallable();

return new Response(200, [], call_user_func_array($callable, [$request]));

class MyClass 
{
    public function __invoke(ServerRequestInterface $request)
    {
        return 'Hello World';
    }
}

Return New Response(200, [], call_user_func_array(new MyClass(), [$request]));

class MyClass 
{
    public function myMethod(ServerRequestInterface $request)
    {
        return 'Hello World';
    }
}

Return New Response(200, [], call_user_func_array([new MyClass(), 'myMethod'], [$request]));

new \Hulotte\Middlewares\RoutingMiddleware($dispatcher);

$routingMiddleware = new \Hulotte\Middlewares\RoutingMiddleware($dispatcher);
$routingMiddleware->setNotFoundCallable(function(){
    return 'Oups, not found !';
});