PHP code example of pvettori / router

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

    

pvettori / router example snippets


use PVproject\Routing\Route;
use PVproject\Routing\Router;

Router::create()->addRoute(Route::get('/home', function () {
    http_response_code(200);
    exit('<h1>Home</h1>');
}))->run();

$route = Route::get('/home', function () { echo 'This is the home page.'; });

$router = Router::create()->addRoute($route);

$router->run();

$route = Route::get('/path/{param}', function ($param) {
    echo 'This is the route parameter: '.$param;
});

$route = Route::get('/path', function ($request) {
    echo 'This is the HTTP method: '.$request->getMethod();
});

$router = Router::create()->setPrefix('/admin');
$router->setRoute('/login' function () {
    echo 'This route is /admin/login';
});

$route = Route::create('/path', function () { /* code */ }, ['PUT', 'PATCH']);
// alternative way
$route = Router::create()->setRoute('path/', function () { /* code */ }, ['PUT', 'PATCH']);

$route = Route::get('/path', '\ActionClass->action');
$route = Route::get('/path', '\ActionClass::staticAction');
$route = Route::get('/path', '\InvokableClass');

function middleware_function($request, $handler) {
    // code executed before next handler...
    $response = $handler($request);
    // code executed after next handler...

    return $response;
}

class MiddewareClass extends \PVproject\Routing\Middleware {
    public function __invoke(
        RequestInterface $request,
        callable $handler
    ): ResponseInterface {
        // code executed before next handler...
        $response = $handler($request);
        // code executed after next handler...

        return $response;
    }
}

$route = Route::create('/path', function ($request) { return $response; })
    ->withMiddleware(
        'middleware_function',
        'MiddewareClass'
    );

function middleware_function($request, $handler, $extra) {
    return $response;
}

$route = Route::create('/path', function ($request) { return $response; })
    ->withMiddleware(
        ['middleware_function', 'extra_argument'],
        'MiddewareClass'
    );

$router = Router::create()->addRouteGroup('/admin', [
    Route::create('/login', function ($request) { return $response; })
    Route::create('/home', function ($request) { return $response; })
], [
    ['middleware_function', 'extra_argument'],
    'MiddewareClass'
]);

// arguments passed on Router creation
$router = Router::create([
    'arguments' => [
        'extra1' => 'value1',
        'extra2' => 'value2',
    ]
]);
// arguments passed on Router run
$router = Router::create()->run([
    'extra1' => 'value1',
    'extra2' => 'value2',
]);