问题
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