4.3. Routes Configuration

"Routing" is a pared-down pure-PHP mod_rewrite-alike that can map URLs to controller/action/params and back. It was added to Cake to make pretty URLs more configurable and to divorce us from the mod_rewrite requirement. Using mod_rewrite, however, will make your address bar look much more tidy.

Routes are individual rules that map matching URLs to specific controllers and actions. Routes are configured in the app/config/routes.php file. They are set-up like this:

Example 4.2. Route Pattern

<?php
$Route->connect (
    'URL',
    array('controller'=>'controllername',
    'action'=>'actionname', 'firstparam')
);
?>


Where:

Any parameters following firstparam will also be passed as parameters to the controller action.

The following example joins all the urls in /blog to the BlogController. The default action will be BlogController::index().

Example 4.3. Route Example

<?php
$Route->connect ('/blog/:action/*', array('controller'=>'Blog', 'action'=>'index'));
?>


A URL like /blog/history/05/june can then be handled like this:

Example 4.4. Route Handling in a Controller

<?php
class BlogController extends AppController
{
 function history ($year, $month=null)
 {
   // .. Display appropriate content
 }
}
?>


The 'history' from the URL was matched by :action from the Blog's route. URL elements matched by * are passed to the active controller's handling method as parameters, hence the $year and $month. Called with URL /blog/history/05, history() would only be passed one parameter, 05.

The following example is a default CakePHP route used to set up a route for PagesController::display('home'). Home is a view which can be overridden by creating the file /app/views/pages/home.thtml.

Example 4.5. Setting the Default Route

<?php
$Route->connect ('/', array('controller'=>'Pages', 'action'=>'display', 'home'));
?>