dev-master
9999999-devA functional route dispatcher
MIT
The Requires
The Development Requires
by Woody Gilk
Wallogit.com
2017 © Pedro Peláez
A functional route dispatcher
EitherWay combines the excellent FastRoute
with FP-Either to create an easy to
dispatch routes that resolve to class names or container identifiers., (*1)
composer require shadowhand/either-way
First, create a PSR-7 ServerRequestInterface.
In this example, we will use PSR-17 ServerRequestFactory., (*2)
$request = $serverRequestFactory->createServerRequest($_SERVER);
Next, create a Dispatcher with FastRoute:, (*3)
$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:, (*4)
$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., (*5)
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., (*6)
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., (*7)
Now that all everything is defined, we can execute the routing:, (*8)
use function EitherWay\dispatch;
$response = dispatch($request, $dispatcher)
->either($handleError, $handleSuccess);
At this point, the response can modified and ultimately sent., (*9)
MIT, (*10)
A functional route dispatcher
MIT