Kohana 3 Routes and Requests
Kohana sports a powerful and lean Request class. The most useful I’ve seen of any PHP framework, it essentially takes a regular expression and routes it to the appropriate controller, directory, action, or other value using keys, this allows for some robust URLs and applications. Lets take a look at how to mimic Basecamp style URL’s in Kohana minus the sub domain. If there is interest I’ll add that in a later article, just let me know in the comments, yeah?
Basecamp Project Style Route
Route::set('projects', 'projects/
(/(/(/)))', array(
'project_id' => '\d+'
))->defaults(array(
'controller' => 'log',
'action' => 'index',
));
This route will take a URL like projects/1/, and load up the Controller_Log.php file and fire the action_index. In fact anything after projects/1/ will be fired like the default route. So this allows you to use, projects/1/todos/add and fire the action_add in the Controller_Todos.php file. Even better if you want to scope your todos to the project referenced in the URL, you can set the project in the controllers before() method:
public function before()
{
parent::before();
$property = ORM::factory('project')
->where('id','=', $this->request->param('property_id'))
->where('user_id', '=', $this->user->id)
->find();
if($property->loaded())
{
$this->property = $property;
$this->template->property = $property;
}
else
{
// Couldn't find the project
$this->request->redirect('/');
}
}
Notice I grabbing the parameter from the URL using the param() method in the Request class using the specified key in the route.
$this->request->param('project_id');
You could grab any parameter this way:
$this->request->param('id');
Using this method in your actions allows you to never pass parameters to your functions again, thus you can change the order of your routes and the site will function the exact same way.
Kohana Framework