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?

Answers


The controller has access to the MvcEvent 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');

   });
}

Need Your Help

Obj-C: Creating an object with a String name

iphone objective-c string class

Hey all. I know this sounds simple, but I can't find a way to do it. I have a method in Obj-C that takes in a NSString and then should create a new class with the String as its title.

Collapse navigation bar issue in bootstrap 3

twitter-bootstrap-3 navbar collapse

Went through some suggestion like adding navbar-right, but still getting it.