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.

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 use the Router to use custom prefixes for uses beyond admin routing, 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. Also important to remember, using the HTML helper to build your links will help maintain the prefix calls. Here's an example link being built using the HTML helper:

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

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