Tips and tricks: changing the controller method
- Posted by dlib on June 19th, 2008 filed in Ajax, Code examples, Kohana, Medium
Occasionally I like to post about a small tricks and tips in Kohana. Today I’ll cover changing the controller method. There are already ways to change how the controller method calling works. Having a _remap() method can change the functionality of the controller completely for example. Or the _default() method, called when the requested controller method cannot be found.
This is not all though, for example the following.
//controllers/student.php class Student_Controller extends Controller{ public function __construct() { parent::__construct(); if(request::is_ajax()) { Router::$method='ajax_'.Router::$method; } } public function ajax_delete(){} }
Now, if you request example.com/student/delete through an ajax request, internally you’ll be routed to Student_Controller::ajax_delete()
Other options could be that you route student/overview/rss not to the ‘overview’ method but to some specific rss method.
Besides the above method of changing the controller method, there is also an event you can use.
Enable hooks by setting config/hooks.php -> $config['enable'] to true. Create a file ‘hook.php’ in your hooks directory. Fill it with the following:
Event::add('system.pre_controller','hook'); function hook(){ if(request::is_ajax()) { Router::$method='ajax_'.Router::$method; } }
This will prepend ajax_ to all requests that are ajax requests. You can also hook into another event in revisions 2833 and up.
//controllers/student.php class Student_Controller extends Controller{ public function __construct() { parent::__construct(); Event::add('system.post_controller_constructor',array($this,'ajax')); } public function ajax() { if(request::is_ajax()) { Router::$method='ajax_'.Router::$method; } }
All different ways to accomplish the same thing. I hope it can help you.
June 19th, 2008 at 12:14 pm
Is it just me, or is directly writing to a Library variable weird/hacky? (Referring to Router::$method=)
June 19th, 2008 at 12:22 pm
Lick:
I wouldn’t say so. Those variables are public exactly because we should write to them if necessary.
I’d say that most of hooks are for writing to some core or library objects variables.
June 19th, 2008 at 2:31 pm
Yeh that is the point between public and private vars