I have been working in Zend Framework for a while and I am currently refactoring some parts of my code. One of the big thing I would like to eliminate is my abstract
controller class which initiate a lot of variables which must be present in all my controller such as $success
, $warning
and $error
. This part can be done in controller pluggins but what would be the best way to send these variables to the related view. Currently I am 开发者_Go百科using a custom method in my abstract
controller class which i call from within all my controllers.
protected function sendViewData(){
$this->view->success = $this->success;
$this->view->warning = $this->warning;
$this->view->error = $this->error;
}
which is then called in all the actions of all of my controllers throught
parent::sendViewData();
I was looking to automate this process through a plugin controller or anything better suited for this
You could set a postDisplatch method in your abstract controller to initialize the view data (See section "Pre- and Post-Dispatch Hooks").
That way, in each actions, you could initialize your $this->success
, $this->warnning
or $this->error
variables, and it would be pass to the view after the action is executed.
The Best pactice is, define a base controller and let other controllers to extend this, instead of directly calling the Zend_Controller_Action
method
// Your base controller file ApplicationController.php
class ApplicationController extends Zend_Controller_Action {
// method & variable here are available in all controllers
public function preDispatch() {
$this->view->success = $this->success;
$this->view->warning = $this->warning;
$this->view->error = $this->error;
}
}
Your other normal controllers would be like this
// IndexController.php
class IndexController extends ApplicationController {
}
Now these (success, warning & error) variable are available in all views/layout files, In ApplicationController.php
you can also hold shared functionality of other controllers.
精彩评论