How to run the same lines in all init () functions of controllers?

I need the same 2 lines in all my controllers, each controller has its own initialization logic, but these two lines are common to all of them.

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

How can I avoid code repetition?

Update:

Well, FlashMessenger was just an example, let's say I need to write a log line in every action, except for 'someAction' @ 'someController'. So, 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);

, , init() . ?. : "someAction". "BaseController" . : ? ( : Class 'BaseController' ).

+3
5

:

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

.

Edit:

, Controllers, :

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

, :

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

- ( , )

$fm = new Zend_Controller_Action_Helper_FlashMessenger();
Zend_Debug::dump($fm->getMessages());

, , http://grummfy.be/blog/191

+1

:

protected function _initMyActionHelpers() {
    $fm = new My_Controller_Action_Helper_FlashMessenger();
    Zend_Controller_Action_HelperBroker::addHelper($fm);;
}
0

?

, init , .

, @Jeff (. ), . :

$this->_helper->flashMessanger('My message');

.

-1

This is not a reason to create a new user controller. Just add this line to all init () methods.

$this->view->messages = $this->_helper->getHelper('FlashMessenger')->getMessages();
-1
source

Source: https://habr.com/ru/post/1793138/


All Articles