在URL中传递多个变量-Yii2

问题描述:

我想生成可处理多个参数的URL,如下所示.

I want to generate URL's that can handle multiple parameters as follows.

www.mysite.com/index.php/controller/param1/param2/param3/param4/mySlug 

但是仍然能够灵活地传递较少的信息

But still be able to be flexible and pass over less information

www.mysite.com/index.php/controller/param1/parama/my_slug_2 

如果可以简化,我们可以假设最后总是有一个. Yii2 urlManager中有什么我可以实现的东西.

We could assume there's always a slug at the end if that makes this easier. Is there anything in the Yii2 urlManager I can implement this.

只需使用以下参数的默认值配置规则:

Just configure your rule with default values of your params like this:

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            [
                'pattern' => 'test/<param1:\d+>/<param2:\d+>/<param3:\d+>/<param4:\d+>/<slug>',
                'route' => 'site/test',
                'defaults' => [
                    'param1' => null,
                    'param2' => null,
                    'param3' => null,
                    'param4' => null,
                ]
            ]
        ]
    ],

所有具有默认值的参数不是必需的,可以跳过.以下是行为示例:

All the parameters, that have default value are not required and may be skipped. Here are the examples of behaviour:

http://yii2.local/test/slug :

skipped.array (size=5)
  'param1' => null
  'param2' => null
  'param3' => null
  'param4' => null
  'slug' => string 'slug' (length=4)  

http://yii2.local/test/2/4/slug

array (size=5)
  'param1' => string '2' (length=1)
  'param2' => string '4' (length=1)
  'param3' => null
  'param4' => null
  'slug' => string 'slug' (length=4)