At first when I looked into using Kohana I was quite happy and comfortable to use it. As a matter of fact, I still am.

Routing was one thing that I had some trouble with.

Now I don’t know if it was because when I read through some of the articles online and/or forum posts that my mind was hazy with coffee… could be.

Recently I was once again into some code that had been worked on for a project using Kohana v3. And at once the issue of routes had come to mind….. I had always thought about making some kind of “catch all” to avoid errors and such for missing controllers…etc.

But while reading a bit (with a fresh cup of coffee I might add) it just struck me in a different way. I don’t know why I didn’t seem to understand it before…. but I now understood that I could set up various  routes allowing access to controllers and also using a “catch all” of sorts. And the way Kohana uses it’s modules, I could create an init.php file inside  each module directory to define the routes instead of messing with the bootstrap.php file.

Essentially, you can create conditional routes for your modules. This is something that totally slipped away from me when I was working with this prior.

For instance, I setup my routes without the default (out of the box) route.
[code lang=”php”]
Route::set(‘control’, ‘((/(/)))’,array(‘controller’=>'(controller1|controller2|controller3)’))
->defaults(array(
‘controller’ =>’controller1′,
‘action’ => ‘index’,
));
[/code]

Limiting the controllers to the specific controllers used in the application.

There was also one  section of this application that used a simple variable and wanting to keep the URL short, I opted to create a route for it. This variable only had 3 possible values, so the route was also performing some valuable validation.
[code lang=”php”]
Route::set(‘varpage’, ‘()’, array(‘var’ => ‘(cat|dog|turtle)’))
->defaults(array(
‘controller’ => ‘varcontroller’,
‘action’ => ‘view_animal’,
));
[/code]
This isn’t the actual code but the idea remains. This route (above) only allows 3 possible values for <var>.  This route also sets the controller and action to use which in the above example is “varcontroller” and “view_animal”.

Finally, as the deault route, I set up a kind of catch all similar to this
[code lang=”php”]
Route::set(‘default, ‘‘, array(‘stuff’ => ‘.*’))
->defaults(array(
‘controller’ => ‘catch’,
‘action’ => ‘thisaction’,
));
[/code]
Basically what my catch all did was redirect the user if there was URL that was used that went nowhere…. instead of tripping over a missing controller…etc.
This may not be a best practice and the examples I used were just examples.

Remember to define your routes above Kohana’s default route (or a default you set up).

For more on Routing and Kohana, there’s lot’s of great info over here http://kohanaframework.org/guide/about.kohana and here http://kerkness.ca/wiki/doku.php

[ad code=1 align=center]