1

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 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

Charles
  • 50,943
  • 13
  • 104
  • 142
JF Dion
  • 4,014
  • 2
  • 24
  • 34

2 Answers2

5

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.

yvoyer
  • 7,476
  • 5
  • 33
  • 37
  • 1
    but keep in mind that you have to call parent::postDispatch() in your concrete controller if you override the postDispatch method! – Tomáš Fejfar Dec 04 '10 at 12:54
  • So far i wasn't aware of the postDispatch method so i don't have a problem with that, yet, but thanks for pointing out :D – JF Dion Dec 09 '10 at 21:32
2

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.

Ish
  • 28,486
  • 11
  • 60
  • 77