我有以下条件:
1)预期请求是/a1,a2,aN[/.../n1,n2,nN][?range=xxx-yyyy[&search=string]]
(方括号包含可选部分)
2)行动方法签名是public function actionIndex(string $alias = '', string $range = '', string $search = ''): string
3)所以我使用了一个规则:
[
'pattern' => '<alias:[\\w-,\\/]+>',
'route' => 'shop/products/index',
'encodeParams' => false,
],
它正常工作,直到我尝试添加分页,LinkPager
忽略了我写的规则:
[
'pattern' => '<alias:[\\w-,\\/]+>/<page:\d+>',
'route' => 'shop/products/index',
'encodeParams' => false,
],
并将alias
和page
参数显示为GET变量。
什么是正确的规则在/a1,a2,aN/n1,n2,nN/2
等请求URI的末尾添加页码,如果数字为1则忽略?
UPD:我找到了一个理由,这是我之前定义的规则:
'/shop' => 'shop/products/index', //it breaks following rules
[
'pattern' => '<alias:[\\w-,\\/]+>/<page:\d+>',
'route' => 'shop/products/index',
'encodeParams' => false,
],
[
'pattern' => '<alias:[\\w-,\\/]+>',
'route' => 'shop/products/index',
'encodeParams' => false,
],
那么,我如何使所有这些规则一起工作?
解决方案1:制作另一个没有alias
参数的动作方法,并用空的方法调用actionIndex
。
解决方案2:以特殊顺序使用不同的mode
制定相同的规则:
[
'name' => 'This rule is first when we create a link',
'pattern' => '<alias:[\\w-,\\/]+>/<page:\d+>',
'route' => 'shop/products/index',
'encodeParams' => false,
'mode' => \yii\web\UrlRule::CREATION_ONLY,
],
[
'name' => 'This rule is first when we parse a request',
//
'pattern' => 'shop/<page:\d+>',
'route' => 'shop/products/index',
],
[
'name' => 'Used for parsing when previous rule does not match',
'pattern' => '<alias:[\\w-,\\/]+>/<page:\d+>',
'route' => 'shop/products/index',
'encodeParams' => false,
'mode' => \yii\web\UrlRule::PARSING_ONLY,
],
[
'name' => 'Same as first but when link has no page number',
'pattern' => '<alias:[\\w-,\\/]+>',
'route' => 'shop/products/index',
'encodeParams' => false,
'mode' => \yii\web\UrlRule::CREATION_ONLY,
],
[
'name' => 'First when parsing request with no page number',
'pattern' => 'shop',
'route' => 'shop/products/index',
],
[
'name' => 'Used for parsing when previous rule does not match',
'pattern' => '<alias:[\\w-,\\/]+>',
'route' => 'shop/products/index',
'encodeParams' => false,
'mode' => \yii\web\UrlRule::PARSING_ONLY,
],
如果你通过一个动作知道更好的解决方案,我会很高兴看到它。