By now everyone knows that CakePHP version 1.2 has a new and very powerful routing mechanism, similarly the admin routing where URLs like http://blah.com/admin/profiles/add actually calls admin_add action in the profiles controller is also well known. Apart from nice looking URLs Admin routing allows a convenient method to namespace your access control – denying every admin_ action to anyone but those with Admin roles is almost a one liner in your app_controller.
But there are times when you need more than just admin routing, how about something like http://blah.com/user/profiles/edit and http://blah.com/user/profiles/changepassword ? If this could be routed to an action like user_add and user_changepassword wouldn’t it be great!! (eg: think ownership ACL checks)
The CakePHP devs thought that it indeed would be great and have provided a way to do exactly this. In your routes.php write
- Router::connect('/user/:controller/:action', array('prefix' => 'user'));
Yep! thats it… now go ahead and write actions with user_ prefix and they will be called appropriately when there is /user/ in the URL, there is an added bonus – since the html helper now uses the Router to construct URL your links will also automagically have the proper prefix. Thus, if in your view you write
- echo $html->link('Edit your profile', array('controller' => 'profiles', 'action' => 'user_edit'));
the resultant URL in href would be http://blah.com/user/profiles/edit
And yes again you can add as many prefixed routes as you want – so you can very easily have stuff like moderator, editor, manager in the URL with corresponding appropriate actions.
Go! Go crazy

Wow… This is huge! I amaging myself doint a lot of things with that. Thanks for this tip!
I’ve added this info to the documentation as Prefix Routing. Anytime you see something like this, be sure to add it to the documentation.
Thanks Jonathan for updating the cookbook – I intended to but “road to hell is paved…” and all those invalid excuses
Will be faster next time
Thanks. I was playing with configuring something like that in routes.php, didn’t know that it is so easy.
It’s great very helpful…
strange.. this is not working somehow – with the current 1.2 stable (for me anyway)
dont know what is wrong
i have tried
$html->link(‘useredit’, array(‘controller’=>’tests’,'action’=>’test’,'prefix’=>Configure::read(‘Routing.user’)));
with the following in routes:
Router::connect(‘/’. Configure::read(‘Routing.user’) .’/:controller/:action/*’, array(‘prefix’ => Configure::read(‘Routing.user’), Configure::read(‘Routing.user’) => 1));
Configure::read(‘Routing.user’) =>>>> ‘user’;
[i tried it hardcoded as well]
what happens is, that the prefix is not attached to the link
it is just
http://…/tests/test/
instead of
http://…/user/tests/test/
anyone else having some trouble on this matter lately?