Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2 Event Trigger

I'm having an issue getting an event to trigger. Here is my code...

controller.php

function get($id) 
{
    $this->getEventManager()->trigger('hmac.check');
}

When this trigger is ran it will not run the hmac.check event even though it is attached.

module.php

class Module
{
    /**
     * Init the methods
     *
     * @param ModuleManager $moduleManager
     */
    public function init(ModuleManager $mm)
    {
        $mm->getEventManager()
           ->attach(
               'hmac.check',
               function(MvcEvent $evt)
               {
                   echo "The trigger has worked";
                   $key = $evt->getParams()->fromHeader('key');
                   $ts = $evt->getParams()->fromHeader('when');
                   $uri = $evt->getParams()->fromHeader('uri');

                   $hmac = new \Scc\Hmac\Hmac(new HmacConfig, new HmacStorage);
               }
        );
    }
}

If i echo out a message before or after the $mm->getEventManager->attach(); it displays the test fine so i know it is executing the init method.

any help with this would be great.

Thanks in advance

EDIT: This is a restful controller if that makes any difference (i don't think it does).

like image 861
mic Avatar asked May 17 '13 12:05

mic


1 Answers

The problem is that you're attaching listeners to the ModuleManagers EventManager instance, and not the main Application EventManager.

There's no way to attach to the Application EventManager directly from module init(), the module manager doesn't have access to it, so you need to instead get the SharedManager from the ModuleManager's EventManager and attach your event listeners to that.

Here's an example of doing that by listening to the hmac.check event when triggered by any controller that extends Zend\Mvc\Controller\AbstractRestfulController, but you could listen to a specific controller by replacing that with your controllers FQCN instead.

class Module
{
    /**
     * Init the methods
     *
     * @param ModuleManager $moduleManager
     */
    public function init(ModuleManager $mm)
    {
        $mm->getEventManager()->getSharedManager()
           ->attach(
               'Zend\Mvc\Controller\AbstractRestfulController', 'hmac.check',
               function(MvcEvent $evt)
               {
                   echo "The trigger has worked";
                   $key = $evt->getParams()->fromHeader('key');
                   $ts = $evt->getParams()->fromHeader('when');
                   $uri = $evt->getParams()->fromHeader('uri');

                   $hmac = new \Scc\Hmac\Hmac(new HmacConfig, new HmacStorage);
               }
        );
    }
}
like image 98
Crisp Avatar answered Oct 21 '22 18:10

Crisp