6

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?

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
user1820728
  • 61
  • 1
  • 2

1 Answers1

8

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

Community
  • 1
  • 1
Developer
  • 25,073
  • 20
  • 81
  • 128
  • Just as a comment, it would be great if you can shorten your code examples. It is only little helpful to get a bunch of code posted and to figure out everything on your own. Please explain what you're doing (i know it, but questionaire might not) – Sam Nov 13 '12 at 17:14
  • Thanks Sam for reminding me that only bother to answer a question if you have enough time to answer it precisely. otherwise don't waste your time for quick answer. I will keep this in mind and only answer a question if i would have enough time to answer thoroughly. – Developer Nov 14 '12 at 11:18
  • tks so much for your answer. I can do it now. – user1820728 Nov 14 '12 at 17:19
  • For clarity this answer worked, I agree it may help to explain more but it does solve the problem. – jasonsemko Sep 07 '14 at 18:28