Custom URL rules with modules in Yii2

2019-02-24 08:54发布

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条回答
趁早两清
2楼-- · 2019-02-24 09:21

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.

查看更多
登录 后发表回答