This package is abandoned and no longer maintained. No replacement package was suggested.

A functional route dispatcher

1.0.0 2017-03-17 16:58 UTC

This package is auto-updated.

Last update: 2019-08-16 20:58:27 UTC


EitherWay combines the excellent FastRoute with FP-Either to create an easy to dispatch routes that resolve to class names or container identifiers.


composer require shadowhand/either-way


First, create a PSR-7 ServerRequestInterface. In this example, we will use PSR-17 ServerRequestFactory.

$request = $serverRequestFactory->createServerRequest($_SERVER);

Next, create a Dispatcher with FastRoute:

$dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    $r->get('/[{name}]', Acme\WelcomeController::class);

Now define two handlers: one to handle routing errors, and one to handle successful routing:

$handleError = function (int $httpStatus) use ($responseFactory): ResponseInterface {
    return $responseFactory->createResponse($httpStatus);

Note that the error value will be an HTTP status code. How this code is mapped to a response is up to you, the only requirement is that the error handler will return a PSR-7 ResponseInterface.

use EitherWay\Route;

$handleSuccess = function (Route $route) use ($container): ResponseInterface {
    $handler = $container->get($route->handler());
    $response = $handler($route->request());

    return $response;

The EitherWay Route contains two values: the handler string, which is either a class name or a container identifier, and the server request with route parameters attached to it.

Again, how the handler and the request get mapped to a response is up to you, the only requirement is that the handler returns a response.


Now that all everything is defined, we can execute the routing:

use function EitherWay\dispatch;

$response = dispatch($request, $dispatcher)
    ->either($handleError, $handleSuccess);

At this point, the response can modified and ultimately sent.