Kohana 3 :: Routes, URLs, and Links / part 1



Routing

As mentioned in the Request Flow section, a request is handled by the Request class which finds a matching Route and loads the appropriate controller to handle the request. This system provides much flexibility as well as a common sense default behavior.
If you look in APPPATH/bootstrap.php you will see the following code which is run immediately before the request is handed off to Request::instance:
Route::set('default', '(<controller>(/<action>(/<id>)))')
  ->defaults(array(
    'controller' => 'welcome',
    'action'     => 'index',
  ));
This sets the default route with a uri in the format of (<controller>(/<action>(/<id>))). The tokens surrounded with <> are keys and the tokens surrounded with () are optional parts of the uri. In this case, the entire uri is optional, so a blank uri would match and the default controller and action would be assumed resulting in the Controller_Welcomeclass being loaded and eventually the action_index method being called to handle the request.
Notice that in Kohana routes, any characters are allowed aside from ()<> and the / has no special meaning. In the default route the / is used as a static separator but as long as the regex makes sense there is no restriction to how you can format your routes.

Directories

For organizational purposes you may wish to place some of your controllers in subdirectories. A common case is for an admin backend to your site:
Route::set('admin', 'admin(/<controller>(/<action>(/<id>)))')
  ->defaults(array(
    'directory'  => 'admin',
    'controller' => 'home',
    'action'     => 'index',
  ));
This route specifies that the uri must begin with admin to match and the directory is statically assigned to admin in the defaults. Now a request to admin/users/create would load the Controller_Admin_Users class and call theaction_create method.

Patterns

The Kohana route system uses perl compatible regular expressions in its matching process. By default the keys (surrounded by <>) are matched by [a-zA-Z0-9_]++ but you can define your own patterns for each key by passing an associative array of keys and patterns as an additional argument to Route::set. To extend our previous example let's say you have an admin section and an affiliates section. You could specify those in separate routes or you could do something like this:
Route::set('sections', '<directory>(/<controller>(/<action>(/<id>)))',
  array(
    'directory' => '(admin|affiliate)'
  ))
  ->defaults(array(
    'controller' => 'home',
    'action'     => 'index',
  ));
This would provide you with two sections of your site, 'admin' and 'affiliate' which would let you organize the controllers for each into subdirectories but otherwise work like the default route.

0 comments:

Post a Comment