zend framework2 - Pass data to controller from Module.php

414

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?

1

Answer

Solution:

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.

Module.php

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

Controller

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
      $controller->setFoo('bar');

   });
}

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

Source

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.