/fast-route

PSR-15 middleware to use FastRoute

Primary LanguagePHPMIT LicenseMIT

middlewares/fast-route

Latest Version on Packagist Software License Build Status Quality Score Total Downloads SensioLabs Insight

Middleware to use FastRoute for handler discovery.

Requirements

Installation

This package is installable and autoloadable via Composer as middlewares/fast-route.

composer require middlewares/fast-route

You may also want to install middlewares/request-handler.

Example

This example uses middleware/request-handler to execute the route handler:

//Create the router dispatcher
$dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    $r->addRoute('GET', '/hello/{name}', function ($request) {
        //The route parameters are stored as attributes
        $name = $request->getAttribute('name');

        //You can echo the output (it will be captured and written into the body)
        echo sprintf('Hello %s', $name);

        //Or return a string
        return sprintf('Hello %s', $name);

        //Or return a response
        return new Response();
    });
});

$dispatcher = new Dispatcher([
    new Middlewares\FastRoute($dispatcher),
    new Middlewares\RequestHandler()
]);

$response = $dispatcher->dispatch(new ServerRequest('/hello/world'));

FastRoute allows anything to be defined as the router handler (a closure, callback, action object, controller class, etc). The middleware will store this handler in a request attribute.

API

__construct

Type Required Description
FastRoute\Dispatcher Yes The dispatcher instance to use.
Psr\Http\Message\ResponseFactoryInterface No A PSR-17 factory to create the error responses (404 or 405). If it's not defined, use Middleware\Utils\Factory to detect it automatically.

attribute

Changes the attribute name used to store the handler in the server request. The default name is request-handler.

Type Required Description
string Yes The new attribute name
$dispatcher = new Dispatcher([
    //Save the route handler in an attribute called "route"
    (new Middlewares\FastRoute($dispatcher))->attribute('route'),

    //Execute the route handler
    (new Middlewares\RequestHandler())->attribute('route')
]);

$response = $dispatcher->dispatch(new ServerRequest('/hello/world'));

Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.

The MIT License (MIT). Please see LICENSE for more information.