Yii2:如何为UrlManager构建正确的分页模式



我有以下条件:

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,
],

并将CCD_ 4和CCD_。

在请求URI末尾添加页码的正确规则是什么/a1,a2,aN/n1,n2,nN/2,如果数字为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'         => yiiwebUrlRule::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'         => yiiwebUrlRule::PARSING_ONLY,
],
[
'name'         => 'Same as first but when link has no page number',
'pattern'      => '<alias:[\w-,\/]+>',
'route'        => 'shop/products/index',
'encodeParams' => false,
'mode'         => yiiwebUrlRule::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'         => yiiwebUrlRule::PARSING_ONLY,
],

如果你知道一个更好的解决方案,我会很高兴看到它。

最新更新