Search code examples
zend-frameworkcontrollerinitzend-framework-mvc

How to run same lines in all controllers init() function?


I need same 2 lines in all my controllers, each controller have its own init logic, but these two lines are common for all of them.

public function init()
{
    $fm =$this->_helper->getHelper('FlashMessenger');
    $this->view->messages = $fm->getMessages();
}

How can I avoid repeat code ?

Update:

Ok, the FlashMessenger was only an example, let's say I need write a log line in every action except for 'someAction' @ 'someController'. So the new common lines should be.

$this->logger = new Zend_Log();
$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH.'/../logs/log.txt');
$this->logger->addWriter($writer);
$this->logger->log('Some Message',Zend_Log::DEBUG);

The question is, where should I place these lines in order to avoid repeat them in all init() of each controller. These lines should be placed at bootstrap?. If so: How can skip log lines for 'someAction'. Or should I implement a 'BaseController' and make all my controller extend from it. If so: How can I Autoload it? (Fatal error: Class 'BaseController' not found) .


Solution

  • Just subclass the controller:

    class Application_ControllerAction extends Zend_Controller_Action {
        public function init()
        {
            $fm =$this->_helper->getHelper('FlashMessenger');
            $this->view->messages = $fm->getMessages();
        }
    }
    
    
    class IndexController extends Application_ControllerAction {
    }
    

    You may also achieve the same writing Controller Plugin.

    Edit:

    Front controller plugins are executed on each request, just like the Controllers and have the same hook methods:

    routeStartup(): prior to routing the request
    routeShutdown(): after routing the request
    dispatchLoopStartup(): prior to entering the dispatch loop
    preDispatch(): prior to dispatching an individual action
    postDispatch(): after dispatching an individual action
    dispatchLoopShutdown(): after completing the dispatch loop
    

    I addition, you may check controller params to execute the code only on selected requests:

    if ('admin' == $this->getRequest()->getModuleName() 
    && 'update' == $this->getRequest()->getActionName() ) …