PHP code example of wandu / router

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

    

wandu / router example snippets


$dispatcher = new \Wandu\Router\Dispatcher();
$routes = $dispatcher->createRouteCollection();

$routes->get('/', HomeController::class);
$routes->get('/users', UserController::class, 'index');
$routes->get('/users/:id', UserController::class, 'show');

$request = new ServerRequest('GET', '/'); // PSR7 ServerRequestInterface implementation
$response = $dispatcher->dispatch($routes, $request);

static::assertInstanceOf(ResponseInterface::class, $response);
static::assertEquals('index', $response->getBody()->__toString());

$request = new ServerRequest('GET', '/nothing'); // PSR7 ServerRequestInterface implementation
try {
    $dispatcher->dispatch($routes, $request);
} catch (RouteNotFoundException $e) {
    static::assertEquals('Route not found.', $e->getMessage());
}

class HomeController
{
    public static function index()
    {
        return new Response(200, new StringStream("index"));
    }
}

$routes->get('/users/:id(\d+)?', UserController::class, 'show');
$routes->get('/users-:id', UserController::class, 'show');

class UserController
{
    public static function show(ServerRequestInterface $request)
    {
        return new Response(200, new StringStream("{$request->getAttribute('id')}"));
    }
}