0

我怎样才能在路线上做“或”?

例如,/about并且/fr/about指向相同的对象/类/方法。所以而不是:

$app->get('/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

$app->get('/{language:[fr|en]+}/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

我试过这个:

$app->get('/{url:[a-zA-Z0-9\-]+}|/{language:[fr|en]+}/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

我收到此错误:

Type: FastRoute\BadRouteException
Message: Cannot use the same placeholder "url" twice
File: /var/www/mysite/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php

任何想法如何解决这个问题?

或任何避免重复代码的解决方案?

4

2 回答 2

2

这就是为什么您尝试的方法不起作用的原因。

您的路线:

$app->get('/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

$app->get('/{language:[fr|en]+}/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

FastRoute 找到第一个匹配项并分派。如果你看这个,你的第一个路由匹配两者/about/fr/about 所以它首先被调度......事实上,它总是首先调度,总是。

您真正想要的是重新排序路由定义。

$app->get('/{language:[fr|en]+}/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});
// ADD OTHER ROUTES HERE

// CATCH ALL
$app->get('/{url:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});

要解决 URL 重复问题……只需定义一个不同的令牌。

$app->get('/{url:[a-zA-Z0-9\-]+}|/{language:[fr|en]+}/{url2:[a-zA-Z0-9\-]+}', function (Request $request, Response $response, array $args) {
    // same staff
});
于 2016-09-14T19:30:40.920 回答
1

如果您可以更改占位符的顺序,您可以通过以下方式实现它:

$app->get('/{url:[a-zA-Z0-9\-]+}[/{language:[en|fr]+}]', function($request, $response, $args) {
    // code here...
});

通过“更改占位符的顺序”,我的意思是 url 首先出现,然后是语言,所以fr/about你使用about/fr.

该解决方案利用Slim 的内置可选段:注意包装“语言”占位符的方括号。

但是,它要求将可选段放置在路线的末端,否则您会得到FastRoute\BadRouteException.

于 2016-10-02T19:40:04.287 回答