2017 © Pedro Peláez

library router

FastRoute PSR-7 wrapper



FastRoute PSR-7 wrapper

  • Wednesday, March 22, 2017
  • by atanvarno
  • Repository
  • 0 Watchers
  • 0 Stars
  • 15 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 4 Versions
  • 0 % Grown



Software License Latest Version Build Status Coverage Status, (*1)

A PSR-7 wrapper for FastRoute., (*2)


PHP >= 7.0 is required, but the latest stable version of PHP is recommended., (*3)


$ composer require atanvarno/router:^0.2.0

Basic Usage

Two routers are provided: SimpleRouter and CachedRouter. These both implement the Router interface., (*4)


// A simple, non-caching, router:
use Atanvarno\Router\SimpleRouter;
$router = new SimpleRouter();

// A caching router:
use Atanvarno\Router\CachedRouter;
$router = new CachedRouter();

By default, the GroupCountBased FastRoute driver is used. Other drivers may be specified in the router constructor using the Router::DRIVER_* constants., (*5)

See SimpleRouter::__construct() and CachedRouter::__construct()., (*6)

Defining routes

Routes can be defined by using the add() method, the addGroup() method or via constructor injection. There are also shortcut methods for every HTTP method., (*7)


$router->add($method, $pattern, $handler);

The $method is an uppercase HTTP method string for which a certain route should match. It is possible to specify multiple valid methods using an array. There is a Router::METHOD_* constant for each valid HTTP method., (*8)

By default the $pattern uses a syntax where {foo} specifies a placeholder with name foo and matching the regex [^/]+. To adjust the pattern the placeholder matches, you can specify a custom pattern by writing {bar:[0-9]+}., (*9)

Custom patterns for route placeholders cannot use capturing groups. For example {lang:(en|de)} is not a valid placeholder, because () is a capturing group. Instead you can use either {lang:en|de} or {lang:(?:en|de)}., (*10)

Furthermore parts of the route enclosed in [...] are considered optional, so that /foo[bar] will match both /foo and /foobar. Optional parts are only supported in a trailing position, not in the middle of a route., (*11)

The $handler parameter does not necessarily have to be a callback, it could also be a controller class name or any other kind of data you wish to associate with the route. Atanvarno\Router only tells you which handler corresponds to your request, how you interpret it is up to you., (*12)

add() implements a fluent interface, allowing multiple calls to be chained., (*13)

See Router::add()., (*14)


You can specify routes inside of a group. All routes defined inside a group will have a common prefix., (*15)

For example, defining your routes as:, (*16)

        [Router::METHOD_GET, '/user/{name}', 'handler']
        [Router::METHOD_DELETE, '/user/{name}', 'handler'],

Will have the same result as:, (*17)

$router->add(Router::METHOD_GET, '/admin/user/{name}', 'handler')
    ->add(Router::METHOD_DELETE, '/admin/user/{name}', 'handler');

addGroup() implements a fluent interface, allowing multiple calls to be chained., (*18)

See Router::addGroup()., (*19)

Constructor injection

Route information can be injected into the Router instance constructor. This parameter accepts an array of arrays containing $method, $pattern and $handler values, like a call to add()., (*20)

This allows routes to be held in a separate configuration file that returns such an array:, (*21)

<?php // routes.php
use Atanvarno\Router\Router;

return [
    [Router::METHOD_GET, '/user[/{id:\d+}[/{name}]]', 'handler'],
    [Router::METHOD_PATCH, '/table/{tid}/{uid}/{data}', 'handler'],

```php <?php // main.php use Atanvarno\Router{Router, SimpleRouter};, (*22)

$router = new SimpleRouter(Router::DRIVER_GROUP_COUNT, include 'path/to/routes.php');, (*23)

[SimpleRouter::__construct()](https://github.com/atanvarno69/router/blob/master/docs/SimpleRouter.md#__construct) and 

#### Shortcut methods
For all the valid HTTP request methods shortcut methods are available. For
$router->get('/get-route', 'get_handler')
    ->post('/post-route', 'post_handler');
// Is equivalent to:
$router->add(Router::METHOD_GET, '/get-route', 'get_handler')
    ->add(Router::METHOD_POST, '/post-route', 'post_handler');

Shortcut methods implement a fluent interface, allowing multiple calls to be chained., (*24)

See Router., (*25)


A request is dispatched by calling the dispatch() method. This method accepts a PSR-7 RequestInterface instance., (*26)

$request = //... define your PSR-7 request.

$result = $router->dispatch($request);

Note that all URI paths are normalised so that they have no trailing slash and begin with a leading slash. All user supplied patterns are likewise normalised., (*27)

dispatch() returns an array whose first element contains a status code. It is one of FastRoute\Dispatcher::NOT_FOUND, FastRoute\Dispatcher::METHOD_NOT_ALLOWED or FastRoute\Dispatcher::FOUND. For the method not allowed status the second array element contains a list of HTTP methods allowed for the supplied request., (*28)

NOTE: The HTTP specification requires that a 405 Method Not Allowed response include the Allow: header to detail available methods for the requested resource. Applications using Router should use the second array element to add this header when relaying a 405 response., (*29)

For the found status the second array element is the handler that was associated with the route and the third array element is a dictionary of placeholder names to their values. For example:, (*30)

// Routing against GET /user/atan/42
[FastRoute\Dispatcher::FOUND, 'handler0', ['name' => 'atan', 'id' => '42']]

See Router::dispatch()., (*31)


Instead of using SimpleRouter you can use CachedRouter., (*32)

CachedRouter requires a PSR-16 cache object as a constructor parameter., (*33)

By default, CachedRouter will take its dispatch data directly from the cache and bypass and routes defined by add() calls or constructor injection. Where no dispatch data is available (for example on the first dispatch() call or if the cache data has expired) CachedRouter will generate dispatch data from the defined routes and store it in the cache., (*34)

If your route configuration has changed and you need to update the dispatch data in the cache, call refreshCache()., (*35)

See CachedRouter., (*36)


All exceptions thrown implement the interface RouterException., (*37)

Rather than supply array results, dispatch() can instead throw exceptions for not found and method not allowed results. MethodNotAllowedException::getAllowed() provides a list of allowed methods for the required Allow: response header., (*38)

The package contains these exceptions: * InvalidArgumentException * MethodNotAllowedException * NotFoundException, (*39)

A Note on HEAD Requests

The HTTP specification requires servers to support both GET and HEAD methods:, (*40)

The methods GET and HEAD MUST be supported by all general-purpose servers, (*41)

To avoid forcing users to manually register HEAD routes for each resource we fallback to matching an available GET route for a given resource. Applications MAY always specify their own HEAD method route for a given resource to bypass this behavior entirely., (*42)

Full API

See API., (*43)

The Versions