ZF2-273: use weakref will lose the listener object

Description

PHP Warning: call_user_func() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in /var/www/html/zf2-demo/vendor/ZendFramework/library/Zend/EventManager/EventManager.php on line 441

I check the code, when some event is triggered, event manager try to fetch callback object from a weakref object, the "real" callback object has been disposed, so event manager got null.

here is the code when some listeners is being attached, a listener object is created and pass to attach():


$moduleAutoloader = new ModuleAutoloader($options->getModulePaths());
$this->listeners[] = $events->attach('loadModules.pre', array($moduleAutoloader, 'register'), 1000);
// $moduleAutoloader will be disposed at the end of the function if no other hard reference point it.

here is the code in attach() method, a CallbackHandler is created with $callback as its argument:


public function attach($event, $callback = null, $priority = 1)
{
    // ......
    $listener = new CallbackHandler($callback, array('event' => $event, 'priority' => $priority));
    // ......
}

here is the code when a CallbackHandler is being constructed, only weakref object is keeped. When we retrive "real" object from weakref, if "real" object has been disposed, we got null. I think we do not expect this.


// We have an array callback with an object as the first argument;
// pass it to WeakRef, and then register the new callback
$target = new WeakRef($target);
$this->callback = array($target, $method);

Comments

I fix it, pull request is here: https://github.com/zendframework/zf2/pull/1234

PR merged