Skip to content
Alex edited this page Aug 28, 2019 · 4 revisions

Fluff 包含了一个高效的路由,将 controller 绑定为路由数据,就可以根据不同的 http 请求响应不同的结果。

use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\ServerRequest;
use ConstanzeStandard\Fluff\Application;
use Psr\Http\Message\ServerRequestInterface;

$app = new Application();

$app->withRoute('GET', '/hello', function (ServerRequestInterface $request) use ($app) {
    $queryParams = $request->getQueryParams();
    $response = new Response();
    $response->getBody()->write('Hello ' . $queryParams['who']);
    return $response;
});

$app->start(new ServerRequest('GET', '/hello?who=World'));

当你使用路由时,application 将会变成一个 http 应用,使用 'withRoute' 方法注册路由数据,然后,将一个 PSR-7 server-side request 对象传入 start 方法启动应用。

http method

你可以使用 Application::withRoute 方法的第一个参数绑定一个或多个 http method,http method 必须为字符串或仅包含字符串的数组。

$app->withRoute('GET', ...);

$app->withRoute(['GET'. 'POST'], ...);

当接收到 http 请求时,路由将会检查请求的 http method 是否包含在路由参数中。

你也可以使用代理 Application 的代理方法简化路由的编写:

$app->get(...);  // same with `$app->withRoute('GET', ...);`

Application 支持 4 种代理方法,分别是:get, post, 'put', 'delete'. 这些代理方法省略了 withRoute 的第一个参数。

pattern

Application::withRoute 的第二个参数为 URL 的匹配模式 (pattern)。pattern 可以是一个普通的 URL 字符串。

$app->withRoute('GET', '/user', ...);

也可以包含 URL 参数,参数用 {参数名称} 的形式标识:

$app->withRoute('GET', '/user/{id}', ...);  // 将 id 标识为 URL 参数

controller

Application::withRoute 的第三个参数为 controller。当请求与 route 相匹配时,Application 将会调用 controller,并将 URL 参数作为 controller 的参数传入。

$app->withRoute('GET', '/user/{id}', function($id) {
    return new Response();
});

controller 必须返回一个 Psr\Http\Message\ResponseInterface 对象,之后 Application 会根据 response 所包含的数据应答请求。

选项 (options)

Application::withRoute 的第四个参数为 options,是当前 route 的额外选项,包括 route 名称、中间件列表、过滤器等。

$app->withRoute('GET', '/user/{id}', 'controller', [
    'name' => 'user.profile'
]);

可以利用 Application 中的 routeParser 组件根据 route 名称获取对应的 URL:

$routeParser = $app->getRouteParser();
$routeParser->getUrlByName('user.profile', ['id' => 10]);
// /user/10

路由组

路由组可以为一组路由创建公共的数据,包括 pattern 前缀和共同的路由选项:

$app->withGroup('/user', [
    'middlewares' => ['Auth']
], function($router) {
    $router->get('/profile', 'profileController', [
        'name' => 'user.profile',
        'middlewares' => ['ProfileMiddleware']
    ]);

    $router->get('/create', 'createController', [
        'name' => 'user.create',
        'middlewares' => ['CreateMiddleware']
    ]);
});

如上所示,user.profile 和 user.create 两个 route 都有 Auth 中间件,并且 URL 的前缀都是 /user,用路由组表示比较简洁。

替换系统路由

Fluff 预留了接口,让你有机会替换系统路由,只要将 ConstanzeStandard\Fluff\Interfaces\HttpRouterInterface 作为索引,将新的路由写入 container 即可:

use ConstanzeStandard\Fluff\Interfaces\HttpRouterInterface;

class CustomerRouter implements HttpRouterInterface {
    ...
}

$container->set(HttpRouterInterface::class, new CustomerRouter());