使用 unlimited Optional segments,意味着每个后续段都是保留的。
在您为/news[/{params:.*}] 定义的路线中,以下路径符合条件:
/news
/news/foo
/news/foo/bar
/news/foo/bar/...
因此,如果在方括号之后添加一个额外的固定段 /details,它将不起作用。
当您将其定义为/news[/{params:.*}/details] 并在方括号内使用/details 段时,它确实适用于详细信息,但不能与第一条路线结合使用& 会中断。您仍然可以使用您的第一条路线并检查最后一个参数,或者使用可选参数:
$app->get('/news[/{params:.*}[/details]]', function ($request, $response, $args) {
$params = explode('/', $request->getAttribute('params'));
if (end($params) != 'details') {
$response->write("news!");
} else {
// $params for details;
array_pop($params);
$response->write("news details");
}
// $params is an array of all the optional segments
var_dump($params);
});
更新:
这里的实际问题似乎是路由中的冲突定义,例如,无限的可选段将始终与第二个定义的路由匹配。可以通过使用 route regex 定义路由并在非冲突匹配之前将它们包含在 route group 中来解决:
$app->group('/news', function () {
$this->map(['GET'], '', function ($request, $response, $args) {
$response->write("news w/o params");
})->setName('news');
// Unlimited optional parameters not ending with "/details"
$this->get('/{params:[[:alnum:]\/]*[^\/details]}', function ($request, $response, $args) {
$params = explode('/', $request->getAttribute('params'));
var_dump($params);
$response->write("news!");
});
// Unlimited optional parameters ending with "/details"
$this->get('/{params:[[:alnum:]\/]*\/details}', function ($request, $response, $args) {
$params = explode('/', $request->getAttribute('params'));
array_pop($params); // fix $params
var_dump($params);
$response->write("news details");
});
});