Yii2:如何为UrlManager建立带有分页的正确模式?

时间:2018-07-22 15:40:44

标签: php yii2

我有以下条件:

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

并将aliaspage参数显示为GET变量。

什么是在请求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 个答案:

答案 0 :(得分:0)

解决方案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,
],

如果您知道一个解决方案会更好,那么我将很高兴看到它。