Yii2 中带有模块的自定义 URL 规则 [英] Custom URL rules with modules in Yii2
问题描述
我一直在环顾四周,但没有找到我需要的东西.基本上,我有一些只有 DefaultController 的小模块和一些带有多个控制器的大模块.我对小模块的规则工作正常,但大模块的规则不会.这是我的规则:
I have been looking around but haven't found what I needed. Basically, I have a few small modules which have just the DefaultController and a few bigger ones with multiple controllers. My rules for the small modules work fine but the ones of the big modules won't. Here are my rules:
'<module:\w+>/<action:\w+>' => '<module>/default/<action>',
'<module:\w+>/<action:\w+>/<id:\d+>' => '<module>/default/<action>',
'<module:\w+>/<controller:\w+>' => '<module>/<controller>/index',
'<module:\w+>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>'
前两条规则工作正常,允许我访问:http://host/news/create
并路由到 news/default/create
.
The first two rules work fine, allowing me to access:
http://host/news/create
and routes to news/default/create
.
最后两个应该执行以下操作:http://host/posts/category
应该路由到 posts/category/index
和http://host/posts/category/create
应该路由到 posts/category/create
The last two are supposed to do the following:
http://host/posts/category
which should route to posts/category/index
and
http://host/posts/category/create
which should route to posts/category/create
遗憾的是,它们似乎不起作用.有什么建议吗?
They do not seem to work, sadly. Any suggestions?
推荐答案
看起来第一条规则将捕获任何与第三条规则匹配的请求.
It looks like the first rule will capture any request that could also match the third one.
从其代表正则表达式的角度考虑:w+/w+
:作为 Yii 中路由的通用规则,更多的规范性规则应该放在上面,而不是更通用的、包罗万象的规则应该在底部.
Think of it in the terms of its representing regex: w+/w+
: as a generic rule for routes in Yii, more prescriptive rules should go on top and less more generic, catch-all rules should be at the bottom.
现在获得你所需要的最好方法是做一些事情:
Now the best way to obtain what you need would be to do something along the lines of:
'<module:news>/<action:\w+>' => '<module>/default/<action>',
'<module:news>/<action:\w+>/<id:\d+>' => '<module>/default/<action>',
'<module:posts>/<controller:\w+>' => '<module>/<controller>/index',
'<module:posts>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>'
通过这种方式,您可以清晰而直接地明确表达每个模块的路线,这也将长期帮助您.
this way you are explicitly expressing the routes for each of the modules in a clear and immediate way which will also help you in the long-term.
这篇关于Yii2 中带有模块的自定义 URL 规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!