php 如何使用别名和 $_GET 参数配置 yii2 urlManager 规则
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27316780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to config yii2 urlManager rules with aliases and $_GET parameter
提问by ESCOBAR
for my current (advanced) yii2-based project i just need one controller (SiteController). So there is no need to show it in the url. Thats why i added this rule to the frontend config:
对于我当前的(高级)基于 yii2 的项目,我只需要一个控制器(SiteController)。所以不需要在 url 中显示它。这就是我将此规则添加到前端配置的原因:
'urlManager' => [
'rules' => array(
'<alias:product|contact|about>' => 'site/<alias>',
),
This is working fine and localhost/productpoints to localhost/site/product.
这工作正常,localhost/product指向localhost/site/product。
Of course, i activated prettyUrl and added this default rules to the common config:
当然,我激活了prettyUrl并将这个默认规则添加到了通用配置中:
'rules' => array(
'<controller:\w+>/<id:\w+>' => '<controller>',
'<controller:\w+>/<action:\w+>/<id:\w+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
Now i want to access a GET parameter like this: localhost/product/productname. But i get the error:
现在我想访问这样的 GET 参数:localhost/product/productname。但我收到错误:
Unable to resolve the request "product"
无法解决请求“产品”
but localhost/site/product/productnameis working properly... The "productname" should be $_GET['id']. What do i have to change to make this happen?
但是localhost/site/product/productname工作正常......“productname”应该是 $_GET['id']。我必须改变什么才能做到这一点?
Thanks!
谢谢!
回答by soju
Your rules should be before the default ones, and you need 2 rules, e.g. :
您的规则应该在默认规则之前,并且您需要 2 条规则,例如:
'rules' => array(
'<alias:contact|about>' => 'site/<alias>',
'<alias:product>/<id:\w+>' => 'site/<alias>',
'<controller:\w+>/<id:\w+>' => '<controller>',
'<controller:\w+>/<action:\w+>/<id:\w+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
回答by Sepuka
Just define var in your action, for example public function actionProduct($id)
and $id
been is $_GET['id']
例如public function actionProduct($id)
,只需在您的操作中定义 var并且$id
be$_GET['id']