Kohana Reverse Routing

Posted on

Earlier I wrote a post explaining the basics of Kohana Routes and how to use them. Now comes the second part of the tutorial on how to use the built in Kohana reverse routing functionality. Its actually pretty simple and really where the routing system shines.

First, understand how the Kohana routing system works

If you haven’t already, head over to the previous post, explaining the basics of Kohana routes. If you already know that much, good! I will now show you how to use reverse routing.

What is reverse routing?

Reverse routing is basically a way to construct a URL, programmatically. Using reverse routing is an easy way to piece together a URL using the parts that you defined in the route definitions.

Ok, Show me!

It is super simple. In this example, I will create a route that could be used for a URL in the form of http://example.com/category/slug-of-the-article.
This route will match the structure of the example URL I provided.

Route::set('article', '<category>/<slug>')
		'controller' => 'article',
		'action' => 'view',

Now to do the actual reverse routing, woot! First of all, I specified that my url NEEDS two things (a “category” and a “slug”). The keywords between the <> mean that these will be available as variables. These variables can be accessed in your controller like so:

public function action_index()
    $slug = $this->request->param('slug');
    $category = $this->request->param('category');

So now that we have a route to direct requests to, let me explain how to do it. If you see when you define your route, with Route::set('routename');. ‘routname’ is how Kohana will know what structure to build our route as. Since ours is named ‘article’, we can get that route by going:


Now since we didn’t include any of the parameters in the route inside of parentheses, both keywords are required. So lets create a route with the structure http://example.com/kohana/how-to-use-kohana-routes.

$slug = 'how-to-use-kohana-routes';
$category = 'kohana';
$route = Route::get('article')->uri(array('category' => $category, 'slug' => $slug));

$route would be equal to kohana/how-to-use-kohana-routes. Now you can use this method of reverse routing in your views inside of a helper function to create an absolute url.

I like to create links like so:

<a href="<?php URL::site(Route::get('article')->uri(array('category' => 'kohana', 'slug' => 'how-to-use-kohana-routes'))); ?>">Kohana Routing Article</a>


Once you master the routing system in Kohana, you will quickly realize how much power the framework has. I have grown to absolutely love Kohana greatly in part because of the Routing system. There is still one more thing I need to tell you guys about the routing system though. There is a way to tell Kohana what your URL parameters must match, like a regex in order to create a valid route. But that will have to wait for another time. Thanks and Happy Coding 🙂