CakePHP Reverse Routing

CakePHP provides a very strong and flexible routing engine, for both routing, and reverse routing. Creating a route for the home page is as simple as adding the following line to your routes.php configuration file.

Router::connect('/about_us', array('controller' => 'pages', 'action' => 'display', 'about_us'));

Now, anyone visiting http://example.com/about_us page, will see the view defined in your Pages controller, and the about_us view. This is a very simple example, but leads us to the topic of reverse routing.

We can easily create a link to the about_us page in our markup very easily with the following:

<a href="/about_us">About Us</a>

However, CakePHP provides us with a way to do this through reverse routing and the HTML helper.

<?php $html->link('About Us', array('controller' => 'pages', 'action' => 'display', 'about_us'); ?>

Will generate the following output.

<a href="/about_us">About Us</a>

And, if we later update the route defined in the beginning to a more detailed url, for SEO purposes:

Router::connect('/about-seth-cardoza', array('controller' => 'pages', 'action' => 'display', 'about_us'));

We will not have to update the $html->link(); because the reverse routing takes care of that for us.

This is just a brief introduction to the power and capabilities of CakePHP’s routing and reverse routing. I recommend you read more about CakePHP’s routing in their online manual.