Skip to content


Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?


Failed to load latest commit information.
Latest commit message
Commit time
November 29, 2019 13:53
November 29, 2019 13:53
October 9, 2016 12:54
November 29, 2019 13:53
November 29, 2019 13:53
November 29, 2019 13:53
December 2, 2020 01:05
January 13, 2018 12:13
November 29, 2019 13:53
October 21, 2021 15:53
December 1, 2020 23:58
September 2, 2017 18:26
September 2, 2017 18:26


Latest Version on Packagist Software License Testing Total Downloads

Middleware to use FastRoute for handler discovery.



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.


This example uses middlewares/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.


Create the middleware with a FastRoute\Dispatcher instance:

$route = new Middlewares\FastRoute($dispatcher);

Optionally, you can provide a Psr\Http\Message\ResponseFactoryInterface as the second argument, that will be used to create the error responses (404 or 405). If it's not defined, Middleware\Utils\Factory will be used to detect it automatically.

$responseFactory = new MyOwnResponseFactory();

$route = new Middlewares\FastRoute($dispatcher, $responseFactory);


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

$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())->handlerAttribute('route')

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

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