Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 932
user1820728 Avatar asked Nov 13 '12 11:11

user1820728


1 Answers

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

like image 153
Developer Avatar answered Oct 07 '22 19:10

Developer