PreDispatch does not work

I have few problems, I have a controller that extends AbstractActionController, and I need to call some function before any action, like indexAction. I think preDispatch () calls the call before any action, but when I try to use this code in $ this-> view-> test nothing.

class TaskController extends AbstractActionController { private $view; public function preDispatch() { $this->view->test = "test"; } public function __construct() { $this->view = new ViewModel(); } public function indexAction() { return $this->view; } } 
+6
source share
3 answers

When I want to do this, I use the specific onDispatch method:

 class TaskController extends AbstractActionController { private $view; public function onDispatch( \Zend\Mvc\MvcEvent $e ) { $this->view->test = "test"; return parent::onDispatch( $e ); } public function __construct() { $this->view = new ViewModel(); } public function indexAction() { return $this->view; } } 

Also, see http://mwop.net/blog/2012-07-30-the-new-init.html for more information on how to work with the send event in ZF2.

+13
source

You better do this on the module class and use EventManager to handle the mvc event as follows:

 class Module { public function onBootstrap( $e ) { $eventManager = $e->getApplication()->getEventManager(); $eventManager->attach( \Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 100 ); } public function preDispatch() { //do something } } 
+7
source

And in one line:

 public function onBootstrap(Event $e) { $e->getTarget()->getEventManager()->attach('dispatch', array($this, 'someFunction'), 100); } 

The last number is weight. Like minus equal post event.

The following event is preconfigured:

 const EVENT_BOOTSTRAP = 'bootstrap'; const EVENT_DISPATCH = 'dispatch'; const EVENT_DISPATCH_ERROR = 'dispatch.error'; const EVENT_FINISH = 'finish'; const EVENT_RENDER = 'render'; const EVENT_ROUTE = 'route'; 
+2
source

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


All Articles