Hello readers today we will discuss on callback methods in cakephp. These methods are very simple and easy to use.
In MVC architecture C stands for controller. Controller is used to manage the logic around a single model. Controllers can be thought of as middle layer between the Model and View. We should keep our controllers thin, and our models fat. This will help us to reuse our code and makes our code easier for testing. Controller’s callback methods (beforeFilter, beforeRender and afterFilter) are very useful, they save our lot of time, they make our code more readable and dry. Controllers method are great, but theyshould remain short(not too big).
beforeFilter() – There are many situations where we need to implement some logic. We want some code executed before every action in our controller, then we can put our code in beforeFilter callback. This function is executed before every action in the controller. We can place our code in this to check for an active session or inspect user permissions. We can use this method to perform logics which need to execute before each controller action triggered.
beforeRender() – This function is executed after controller action logic, but before the view is rendered. We can use this method to perform logic or set view variables that are required on every request. beforeRender() is not commonly used, but it may be needed if we are calling render() function manually before the end of a given action.
afterFilter() – This function is executed after every controller action, and after rendering is complete. This is the last controller funtion to run. Its usage is a little bit different from the usage of the beforeFilter. But it is still simple. We can overwrite the afterFilter() callback function in our controller:
beforeRedirect() – The beforeRedirect method is executed when the controller’s redirect method is called but before any further action. If this method returns false the controller will not continue on to redirect the request.
eg:-
class UserController extends AppController {
public $uses = array('Department', 'User');
public $components = array(
'Security' => array(
'csrfExpires' => '+9 hour'
)
);
public function beforeFilter()
{
parent::beforeFilter();
print " - Called before filer in Controller - ";
}
public function beforeRender() {
parent::beforeRender();
print " - Called before render filter in Controller - ";
}
public function afterFilter() {
parent::afterFilter();
print " - Called after filter in Controller - ";
}
public function beforeRedirect($url, $status = null, $exit = true) {
parent::beforeRedirect($url, $status, $exit);
print "- Logic before redirect -";
}
}
0 Comment(s)