Custom URL rules with modules in Yii2

放肆的年华 提交于 2019-12-01 21:35:13

问题


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>'

The first two rules work fine, allowing me to access: http://host/news/create and routes to news/default/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?


回答1:


It looks like the first rule will capture any request that could also match the third one.

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.



来源:https://stackoverflow.com/questions/27402923/custom-url-rules-with-modules-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!