The documentation covering routes in CakePHP is a bit confusing, and doesn’t quite cover how you can you use paths in the URL as method parameters. I’ll cover how I used them in a recent app in this short article.
Routing in CakePHP is similar to using Apache’s mod_rewrite to give you pretty URLS, for example, mapping:
http://server/item/1 to http://server/items.php?id=1
They are used in Cake so that you don’t require mod_rewrite/Apache to achieve such cleaned-up URLS.
Cake’s route documentation (look under Section 3)
http://manual.cakephp.org/chapter/configuration
In my application I wanted to get rid of the controller/action convention and rather have URLs like http://server/about and http://server/contact that are both served by one controller called Pages
My route file looks like this:
1 $Route->connect('/', array('controller' => 'pages'));
2 $Route->connect('/:action/*', array('controller' => 'pages',
'action' => ':action'));
Line 1 says that any request for the root document should be handled by the Pages controller, and since no action was specified, the method will default to index().
The second line catches one or more path parameters and assigns the first one to :action, and the rest are caught by the asterisk (*) and passed along to the controller.
Example
http://server/about/cars/ford
:action => ‘about’
parameters => ‘cars’, ‘ford’
We then assign this route to the Pages controller, and to the action that was specified as the first path variable.
Inside pages_controller.php, we have something like this:
function about($page = 'default', $type = null) {
//code dealing with parameters
//error checking etc.
$this->render($chosen_page);
}
In our example above, $page will equal ‘cars’ and $type will equal ‘ford’.
In this way you can have one controller serving a variety of different pages, out’ve one action - instead of the usual one action per page convention.