Does the code run before each action in the ZF2 module?

I want to write code to run before each action in my module. I tried connecting to onBootstrap() , but the code runs on other modules as well.

Any suggestions for me?

+4
source share
1 answer

There are two ways to do this.

One way is to create a serice and call it in each controller dispatch method.

 Use onDispatch method in controller. class IndexController extends AbstractActionController { /** * * @param \Zend\Mvc\MvcEvent $e * @return type */ public function onDispatch(MvcEvent $e) { //Call your service here return parent::onDispatch($e); } public function indexAction() { return new ViewModel(); } } 

don't forget to include the following library on top of your code

 use Zend\Mvc\MvcEvent; 

The second way is to do it via Module.php using the send event

 namespace Application; use Zend\Mvc\ModuleRouteListener; use Zend\Mvc\MvcEvent; class Module { public function onBootstrap(MvcEvent $e) { $sharedEvents = $e->getApplication()->getEventManager()->getSharedManager(); $sharedEvents->attach(__NAMESPACE__, 'dispatch', array($this, 'addViewVariables'), 201); } public function addViewVariables(Event $e) { //your code goes here } // rest of the Module methods goes here... //... //... } 

How to create a simple service using ZF2

reference2

reference3

+6
source

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


All Articles