MGP
MGP

Reputation: 653

ZF2 Shared Events

I'm trying to set up an event in one module and trigger it in a controller in another module. I'm using the shared event manager but it seems im doing something wrong..

Module1:

public function onBoostrap(Event $e)
        {
              $sem = $e->getTarget()->getEventManager()->getSharedEventManager();
              $sem->attach('checkSomething', function (){
                          die("checked");
              });
        }

Module2 controller:

 public function checkAction ()
        {
                $this->getEventManager()->trigger('checkSomething');
}

Do you guys know what i may be doing wrong? Or if there is a better (correct) way to do this..

Upvotes: 0

Views: 2438

Answers (2)

Ponsjuh
Ponsjuh

Reputation: 468

The problem in the solution of Yassine is that the event is attached on 'Zend\Mvc\Application'. This event identifier is not available in your controller

You can verify this by executing the following code in a action

print_r($this->getEventManager()->getIdentifiers());

the result will be something like

Array ( 
    [0] => Zend\Stdlib\DispatchableInterface 
    [1] => Zend\Mvc\Controller\AbstractController 
    [2] => Application\Controller\TestController 
    [3] => Zend\Mvc\Controller\AbstractActionController 
    [4] => Application 
)

Now to solve your problem in you module attach the event to the 'Application' identifier and then trigger your event in the action.

so:

/*Module*/
public function onBootstrap($e)
{
    $eventManager = $e->getApplication()->getEventManager();
    $sem          = $eventManager->getSharedManager();

    $sem->attach('Application', 'checkSomething', function () {
        echo "checked";
        /* do more stuff here */
    }, 100);

}
/* a action in a controller */
$this->getEventManager()->trigger('checkSomething');

This should result in

checked

And so you have triggered the event succesfully.

Upvotes: 3

yechabbi
yechabbi

Reputation: 1881

You need to specify the identifier of the resource containing an instance of the event manager. Many classes (Application, ModuleManager...) use their class name as an identifier within their contained EventManager instance.

Your attachment line should then look like this:

$sem->attach('Zend\Mvc\Application','checkSomething', function (){
                      die("checked");
          });

(Update) From the controller you should call the application EventManager:

$this->getServiceLocator()->get('application')->getEventManager()->trigger('chec‌​kSomething');

cheers,

Yassine

Upvotes: 0

Related Questions