"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:
URL is the Cake URL you wish to map, |
controllername is the name of the controller you wish to invoke, |
actionname is the name of the controller's action you wish to invoke, |
and firstparam is the value of the first parameter of the action you've specified. |
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 in /app/views/pages/home.thtml
.