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

Request Parameters

The directory, controller and action can be accessed from the Request instance in either of these two ways:
All other keys specified in a route can be accessed from within the controller via:
The Request::param method takes an optional second argument to specify a default return value in case the key is not set by the route. If no arguments are given, all keys are returned as an associative array.


The established convention is to either place your custom routes in the MODPATH/<module>/init.php file of your module if the routes belong to a module, or simply insert them into the APPPATH/bootstrap.php file above the default route if they are specific to the application. Of course, they could also be included from an external file or even generated dynamically.


Along with Kohana's powerful routing capabilities are included some methods for generating URLs for your routes' uris. You can always specify your uris as a string using URL::site to create a full URL like so:
However, Kohana also provides a method to generate the uri from the route's definition. This is extremely useful if your routing could ever change since it would relieve you from having to go back through your code and change everywhere that you specified a uri as a string. Here is an example of dynamic generation that corresponds to the feeds route example from above:
  'user_id' => $user_id,
  'action' => 'comments',
  'format' => 'rss'
Let's say you decided later to make that route definition more verbose by changing it to feeds/<user_id>(/<action>).<format>. If you wrote your code with the above uri generation method you wouldn't have to change a single line! When a part of the uri is enclosed in parentheses and specifies a key for which there in no value provided for uri generation and no default value specified in the route, then that part will be removed from the uri. An example of this is the (/<id>) part of the default route; this will not be included in the generated uri if an id is not provided.
One method you might use frequently is the shortcut Request::uri which is the same as the above except it assumes the current route, directory, controller and action. If our current route is the default and the uri was users/list, we can do the following to generate uris in the format users/view/$id:
$this->request->uri(array('action' => 'view', 'id' => $user_id));
Or if within a view, the preferable method is:
Request::instance()->uri(array('action' => 'view', 'id' => $user_id));


Post a Comment