我在yii2遇到了一个问题,用一些参数创建一个url,当时每个参数都可能被遗漏。 例如:
site.com/index/param1/value1/param2/valu2/param3/value3/param4/value4
或者:
site.com/param2/value2/param4/value4
只有4个固定名称的参数。我试着搜索这个,但没有找到合适的文档。
public function createUrl ($ manager, $ route, $ params)
{
if ($ route === 'site / index') {
if (isset ($ params ['ship']) OR isset ($ params ['map']) OR isset ($ params ['gamemode']) OR isset ($ params ['version'])) {
return (isset ($ params ['ship']))? $ params ['ship']. '/' ''
. (isset ($ params ['map']))? $ params ['map']. '/' ''
. (isset ($ params ['gamemode']))? $ params ['gamemode']. '/' ''
. (isset ($ params ['version']))? $ params ['version']. '/', '';
}
}
return false;
}
public function parseRequest ($ manager, $ request)
{
$ pathInfo = $ request-> getPathInfo ();
if (preg_match ('% ^ (\ w +) (/ (\ w +))? $%', $ pathInfo, $ matches)) {
}
return false;
}
另外,我无法理解在parseRequest中要做什么以及在哪里使用$ params。
答案 0 :(得分:0)
您可以像这样向urlManager添加一些规则:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
...
'site/param1/<param1:\w+>' => 'site/action',
'site/param2/<param2:\w+>' => 'site/action',
'site/param3/<param3:\w+>' => 'site/action',
'site/param4/<param4:\w+>' => 'site/action',
'site/param1/<param1:\w+>/param2/<param2:\w+>' => 'site/action',
'site/param1/<param1:\w+>/param3/<param3:\w+>' => 'site/action',
'site/param1/<param1:\w+>/param4/<param4:\w+>' => 'site/action',
'site/param2/<param2:\w+>/param3/<param3:\w+>' => 'site/action',
'site/param2/<param2:\w+>/param4/<param4:\w+>' => 'site/action',
'site/param3/<param3:\w+>/param4/<param4:\w+>' => 'site/action',
'site/param1/<param1:\w+>/param2/<param2:\w+>/param3/<param3:\w+>' => 'site/action',
'site/param1/<param1:\w+>/param2/<param2:\w+>/param4/<param4:\w+>' => 'site/action',
'site/param1/<param1:\w+>/param3/<param3:\w+>/param4/<param4:\w+>' => 'site/action',
'site/param2/<param2:\w+>/param3/<param3:\w+>/param4/<param4:\w+>' => 'site/action',
'site/param1/<param1:\w+>/param2/<param2:\w+>/param3/<param3:\w+>/param4/<param4:\w+>' => 'site/action',
...
这可能不是最优雅的方式,但它仍然有效。当有更多参数时会出现主要问题。