Search code examples
eventszend-framework2

ZF2 Remove anonymous function from event manager


In my module's onBootstrap function I have attached an anonymous function that is hooking into the dispatch.error event (for logging purposes):

$eventManager->attach('dispatch.error', function($e) {
    //Code here
});

I am now setting up Unit Tests and do not want the logging function to run on test requests.

How do I remove this anonymous function from the event manager?

From the documentation:

attach

[snip]

The method returns an instance of Zend\Stdlib\CallbackHandler; this value can later be passed to detach() if desired.

and

detach

[snip]

Scans all listeners, and detaches any that match $listener so that they will no longer be triggered.

I have therefore altered my attach to:

$logCallBack = $eventManager->attach('...

To what do I save the callback to so that I can remove it in my unit test?

$this->getApplication()->getEventManager()->detach(???);

Solution

  • I have added to the callback to the $_SERVER global variable:

    $logCallBack = $eventManager->attach(['dispatch.error', 'render.error'], function($e) {
        //...
    }
    $_SERVER['logCallBack'] = $logCallBack;
    

    Then where I want to unregister them:

    $callBacks = $_SERVER['logCallBack'];
    if(!is_array($callBacks)) {
        $callBacks = [$callBacks];
    }
    foreach($callBacks as $callback) {
        $this->getApplication()->getEventManager()->detach($callback);
    }