I'm attending CakeFest 2010!

3.4.5.5 Prefix Routing

Many applications require an administration section where privileged users can make changes. This is often done through a special URL such as /admin/users/edit/5. In CakePHP, admin routing can be enabled from within the core configuration file by setting the admin path for Routing.admin.

Configure::write('Routing.admin', 'admin');
  1. Configure::write('Routing.admin', 'admin');

In your controller, any action with an admin_ prefix will be called. Using our users example, accessing the url /admin/users/edit/5 would call the method admin_edit of our UsersController passing 5 as the first parameter. The view file used would be app/views/users/admin_edit.ctp

You can map the url /admin to your admin_index action of pages controller using following route

Router::connect('/admin', array('controller' => 'pages', 'action' => 'index', 'admin' => true)); 
  1. Router::connect('/admin', array('controller' => 'pages', 'action' => 'index', 'admin' => true));

You can configure the Router to use multiple prefixes too:

Router::connect('/profiles/:controller/:action/*', array('prefix' => 'profiles', 'profiles' => true)); 
  1. Router::connect('/profiles/:controller/:action/*', array('prefix' => 'profiles', 'profiles' => true));

Any calls to the profiles section would look for the profiles_ prefix on the method calls. Our users example would have a URL structure that looks like /profiles/users/edit/5 would call the profiles_edit method within the UsersController.

Wildcard prefix routing is available using the named element :prefix similar to :controller and :action. You can map the url /api/user/create to your user_create action of api controller using the following route

Router::connect('/api/:prefix/:action', array('controller' => 'api'));
  1. Router::connect('/api/:prefix/:action', array('controller' => 'api'));

Additionally you can map the url /api/question/create to your question_create action of api controller or /api/question/edit to your question_edit action of api controller.

Also important to remember, using the HTML helper to build your links will help maintain the prefix calls. Here's how to build this link using the HTML helper:

echo $html->link('Edit your profile', array('profiles' => true, 'controller' => 'users', 'action' => 'edit', 'id' => 5)); 
  1. echo $html->link('Edit your profile', array('profiles' => true, 'controller' => 'users', 'action' => 'edit', 'id' => 5));

You can set up multiple prefixed routes using this approach to create a flexible URL structure for your application.