Table of Contents
StatusDraft
TodoExpand, add examples

Routing

Typically, a URI will map to a controller class and method on a one-to-one basis and provide arguments where necessary. For example,

http://www.example.com/class/function/arg1/arg2

The first segment refers to the controller class, the second to a method in that class and any other segments become that method's arguments.

There are cases, however, where you might want to change this behaviour. For example, you may want to use URIs like this: www.example.com/article/22. Here, the second segment of the URI is an article number, which is an argument, not a controller method. The routing feature of Kohana allows you to change how URIs are mapped to controllers and methods.

Kohana's routing configuration

In order to alter routing you have to have a copy of routes.php in your application/config directory. If it is not already there copy the one from the system/config directory.

The default routes.php will have one entry:

$config['_default'] = 'welcome';

$config['_default'] specifies the default route. It is used to indicate which controller should be used when a URI contains no segments. For example, if your web application is at www.example.com and you visit this address with a web browser, the welcome controller would be used even though it wasn't specified in the URI. The result would be the same as if the browser had gone to www.example.com/welcome.

Specifying your own routes

In addition to the default route above, you can also specify your own routes. The basic format for a routing rule is:

$config['route'] = 'class/method';

where route is the URI you want to route, and class/method would replace it.

So, for example, if your Kohana web application were installed at www.example.com and you had the following routing rule:

$config['test'] = 'foo/bar';

and you visited www.example.com/test in a web browser, you would see the page at www.example.com/foo/bar.

Using regular expressions

The route part of a routing rule is actually a regular expression. If you are unfamiliar with regular expressions you can read more about them at the PHP website. Using regular expressions, you can be more selective about which URIs will match your routing rules, and you can make use of the sub-pattern back referencing technique to re-use parts of the URI in it's replacement.

This is best described with an example. Suppose we wanted to make the URL www.example.com/article/22 work, we might use a routing rule like this:

$config['article/([0-9]+)'] = 'news/show/$1';

which would match URIs starting with “article/” followed by some numeric digits. If the URI takes this form, we will use the news controller and call it's show() method passing in the article number as the first argument. In the www.example.com/article/22 example, it is as if the URL www.example.com/news/show/22 had been visited.

Examples

general/routing.txt · Last modified: 2008/08/13 06:55 by spirit