Routing Basics

Kohana 3.0s Route Class provides you with unlimited options on how to map specifically formatted requests to specific controllers and actions.

Routes should be defined in your application/bootstrap.php file or in the modules/mymodule/init.php file by calling the Route::set() method.

Below you can see the default Route that is predefined in the application/bootstrap.php file. Each route must have at minimum a name a uri and a set of defaults for the uri.

  Route::set('default', '(<controller>(/<action>(/<id>)))')
      ->defaults(array(
          'controller' => 'welcome',
          'action' => 'index',
      )); 

This route will handle requests that are formatted in the following manner.

  http://example.php/index.php/<controller>/<action>/<id>

All segments of this URI request are optional. If the segment is not provided the Route will use default values.

Here is the same route but with both the controller and action segments as required instead of optional.

  Route::set('required', '<controller>/<action>(/<id>)')
      ->defaults(array(
          'controller' => 'welcome',
          'action' => 'index',
      )); 
A Basic Custom Route

IMPORTANT: When creating custom Routes they should always be defined before the default route. Your default route should always be defined last in your bootstrap.php.

The following route will direct all requests for example.com/index.php/products/<action>/<id> to the appropriate action of an inventory controller.

  Route::set('products', 'products(/<action>(/<id>))')
      ->defaults(array(
          'controller' => 'inventory',
          'action' => 'index',
      )); 
Basic Route with 2 parameters

Unlike KO2, KO3 Routing default in your bootstrap does not handle 2 or more parameters like example.com/<controller>/<action>/<param1>/<param2>

  Route::set('default', '(<controller>(/<action>(/<id1>(/<id2>))))')
->defaults(array(
	'controller' => 'welcome',
	'action'     => 'index',
));
A Custom Route with no optional segments

The following route will direct all requests for example.com/index.php/custom to the index action of the welcome controller.

  Route::set('custom', 'custom')
      ->defaults(array(
          'controller' => 'welcome',
          'action' => 'index',
      )); 
A Custom Route with one dynamic Segment

The following route will direct request for example.com/index.php/about, example.com/index.php/faq and example.com/index.php/locations to the static action of the page controller.

Route::set('static', '<page>', array('page' => 'about|faq|locations')) 
	->defaults(array( 
		'controller' => 'page', 
		'action' => 'static', 
	));
A Custom Route with id and slug

Must be set before the 'default' route

Route::set('idslug', '<controller>/<action>/<id>-<slug>', array('id'=>'[0-9]+', 'slug'=>'.+'))
	->defaults(array(
		'controller' => 'home',
		'action'     => 'index',
	));
routing/routing_basics.txt · Last modified: 2010/06/20 16:51 by tstrokes