Consolidate CakePHP routes

回眸只為那壹抹淺笑 提交于 2019-12-25 01:19:06

问题


Is there any way to consolidate the following rules into one rule?

Router::connect('/manufacturer/:manufacturer/:friendly0', array('controller'=>'categories', 'action'=>'view'), array('pass'=>array('manufacturer', 'friendly0')));
Router::connect('/manufacturer/:manufacturer/:friendly0/:friendly1', array('controller'=>'categories', 'action'=>'view'), array('pass'=>array('manufacturer', 'friendly0', 'friendly1')));
Router::connect('/manufacturer/:manufacturer/:friendly0/:friendly1/:friendly2', array('controller'=>'categories', 'action'=>'view'), array('pass'=>array('manufacturer', 'friendly0', 'friendly1', 'friendly2')));
Router::connect('/manufacturer/:manufacturer/:friendly0/:friendly1/:friendly2/:friendly3', array('controller'=>'categories', 'action'=>'view'), array('pass'=>array('manufacturer', 'friendly0', 'friendly1', 'friendly2', 'friendly3')));
Router::connect('/manufacturer/:manufacturer/:friendly0/:friendly1/:friendly2/:friendly3/:friendly4', array('controller'=>'categories', 'action'=>'view'), array('pass'=>array('manufacturer', 'friendly0', 'friendly1', 'friendly2', 'friendly3', 'friendly4')));

回答1:


Actually - you don't need to use that many rules:

http://book.cakephp.org/view/945/Routes-Configuration

Essentially when someone will browse to yoursite.com/manufacturer - the manufacturer controller will be called, and since an action isn't defined - it will default to index. So what you could do is just:

Router::connect('/manufacturer/*', array('controller' => 'categories', 'action' => 'view'));

Now when someone browses to yoursite.com/manufacturer - the request is forwarded to the categories controller, calling the view action. The '/*' insures any further parameters are also forwarded there.

So when someone were to visit yoursite.com/manufacturer/iamfriendly/iamfriendlytoo - you can then get those passed paramaters / variables through

$this->params['pass']

Or:

$this->passedArgs

Giving you the following array:

Array
(
    [0] => iamfriendly
    [1] => iamfriendlytoo
)

You can further enhance this by using named parameters, so you receive something like:

Array
(
    ['manufacturer'] => iamfriendly
    ['friendly0'] => iamfriendlytoo
)



回答2:


don't use ':friendly0',':friendly1',':friendly2' etc. It makes them the keys in your url array. That's why you need to pass them again in the 'pass' array.

What Shaz suggests is right:

Router::connect('/manufacturer/*', array('controller'=>'categories', 'action'=>'view'));

If you pass them the way you do it right now, it will be a variable number of arguments in your view() function. Look in pages_controller to see how it handles that. But I would suggest using named arguments instead.



来源:https://stackoverflow.com/questions/6777030/consolidate-cakephp-routes

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