user1820728
user1820728

Reputation: 61

code run before every actions in a module ZF2?

I want to write some code to run before every actions in my module. I have tried hooking onto onBootstrap() but the code run on the other modules too.

Any suggestions for me?

Upvotes: 6

Views: 4230

Answers (1)

Developer
Developer

Reputation: 26243

There are two ways to do this.

One way is to create a serice and call it in every controllers 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 following library on top of your code

use Zend\Mvc\MvcEvent;

Second method is to do this via Module.php using event on dispatch

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 simple service using ZF2

reference2

reference3

Upvotes: 8

Related Questions