PHP code example of pwm / sfw-router

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

    

pwm / sfw-router example snippets


// Router depends on Request
use SFW\Request\Request;
use SFW\Request\RequestMethod as Method;
use SFW\Request\RequestUri as Uri;

// Have some controllers
class FooCtrl
{
    public function getAll(Request $request): array { /* ... */ }
    public function post(Request $request): bool { /* ... */ }
}
class BarCtrl
{
    public function getById(Request $request, $fooId, $barId): Bar { /* ... */ }
}

// Create router
$router = new Router();

// Add routes and corresponding route handlers
$router->add(new Route(new Method(Method::GET), new Uri('/foo')), new RouteHandler(FooCtrl::class, 'getAll'));
$router->add(new Route(new Method(Method::POST), new Uri('/foo')), new RouteHandler(FooCtrl::class, 'post'));
$router->add(new Route(new Method(Method::GET), new Uri('/foo/{id}/bar/{id}')), new RouteHandler(BarCtrl::class, 'getById'));

// Resolve a handler for an incoming request
$routeHandler = $router->resolve(new Route($request->getMethod(), $request->getUri()));

// (Optional) Resolve the handler class from the container and call the handling method 
$response = $container
    ->resolve($routeHandler->getClassName())
    ->{$routeHandler->getMethodName()}($request, ...$routeHandler->getRoute()->getCapturedSegments());