I've a backend module which could only be accessed by authorized members. So I need to check authenticity for all actions and for all controllers. Currently I'm doing it inside preDispatch() functions inside controller classes. So it takes care of all the actions inside that controller. But still I've to do it for all controllers. Is there a place I could check it for all the controllers as well. So basically I want one place authenticity check for whole backend module. Can I do it in bootstrap?
views:
33answers:
2The general convention is to create a controller plugin for this, see: http://framework.zend.com/manual/en/zend.controller.plugins.html. You would register this plugin with your front controller in bootstrap (or application.ini). You'd move your auth logic from your controller preDispatch method into a preDispatch() method into your plugin. You would also need to add a check to the start of the method to see what the current module is, as you would only want your auth checks to run on your backend module.
An alternative approach would be to create a base controller class containing the auth checks that all your backend module controllers extend. Personally I would go with the plugin though - it offers more flexibility in the long run.
If you're using a per-module bootstrap, you could certainly do it there. However, I would recommend keeping it at the controller level.
You can also continue to use the preDispatch()
method, but just move the logic into a controller plugin instead. This will affect the preDispatch()
call for every controller.
# in application.ini
resources.frontController.plugins.authenticator = MyApp_Controller_Plugin_Authenticator
# plugin class
class MyApp_Controller_Plugin_Authenticator extends Zend_Controller_Plugin_Abstract {
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
// check for authenticated user
}
}
Alternatively, you could just define the logic in a base controller that all other controllers inherit from. This is how I typically do it (because I choose when to call _setLoginRequired()
when I need it).
MyApp_Controller_Base extends Zend_Controller_Action
{
public function init()
{
$this->_setLoginRequired();
}
protected function _setLoginRequired();
{
// check for authenticated user
}
}