shadowhand/either-way

该包已被弃用且不再维护。未建议替代包。

功能路由分发器

1.0.0 2017-03-17 16:58 UTC

This package is auto-updated.

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


README

EitherWay 将出色的 FastRouteFP-Either 结合,创建了一个易于分发的路由,该路由解析为类名或容器标识符。

安装

composer require shadowhand/either-way

用法

首先,创建一个 PSR-7 ServerRequestInterface。在本例中,我们将使用 PSR-17 ServerRequestFactory

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

接下来,使用 FastRoute 创建一个 Dispatcher

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

现在定义两个处理器:一个用于处理路由错误,另一个用于处理成功路由

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

请注意,错误值将是一个 HTTP 状态码。如何将此代码映射到响应由您决定,唯一的要求是错误处理器将返回一个 PSR-7 ResponseInterface

use EitherWay\Route;

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

    return $response;
};

EitherWay 的 Route 包含两个值:处理器字符串,它可以是类名或容器标识符,以及附加了路由参数的服务器请求。

同样,处理器和请求如何映射到响应由您决定,唯一的要求是处理器返回一个响应。

分发

现在,所有内容都已定义,我们可以执行路由

use function EitherWay\dispatch;

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

此时,可以修改响应并将其最终发送。

许可

MIT