zend framework2 - Pass data to controller from Module.php


How can I pass data to controllers from Module class?

I need to pass data from onBootstrap method to all module controllers. What is the best way to do this. I can access controller using$e->getTarget() but don't know how to pass custom data to it. Maybe controller has storage for that?




The controller has access to theMvcEvent you can setup an event listener to attach arbitrary data to it and then fetch it within the controller.


public function onBootstrap(MvcEvent $event)
   $event->setParam('foo', 'bar');


public function fooAction() {
  $foo = $this->getEvent()->getParam('foo', false);

@JonDay suggested an event listener which would also work well.

public function onBootstrap(MvcEvent $event)
   $application  = $event->getApplication();
   $eventManager = $application->getEventManager()->getSharedManager();

   $eventManager->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($event) {
      $controller = $event->getTarget();

      // Set public property
      $controller->foo = 'bar';

      // OR protected with setter


People are also looking for solutions to the problem: php - Auto Logout when user leaves the application without doing logout action


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.