Description
Weak references provide a non-intrusive gateway to ephemeral objects. Unlike normal (strong) references, weak references do not prevent the garbage collector from freeing that object. For this reason, an object may be destroyed even though a weak reference to that object still exists. In such conditions, the weak reference seamlessly becomes invalid.
I suggest to use Weak References with Events (with Listeners).
Base idea:
class MyListener
{
public function afterQuery()
{
echo 'Running afterQuery';
}
}
$eventsManager = new Phalcon\Events\Manager();
$myListener = new MyListener();
$eventManager->attachUsingWeakRef('somecomponent', $myListener);
$eventsManager->fire('somecomponent:afterQuery', null);
// this shows "Running afterQuery"
unset($myListener);
// after this step, myListener doesn't have any references anymore and it must die.
$eventsManager->fire('somecomponent:afterQuery', null);
// nothing happens, because myListener has died.
I have three suggests (must be selected only one):
1.Always uses WeakRef for all event-handlers
p.s. But i don't like this solution, because we need strong references in some cases.
$eventsManager = new Phalcon\Events\Manager();
$myListener = new MyListener();
$eventManager->attach('somecomponent', $myListener);
// always use WeakRef for all event handlers.
// can't be uses with strong references
2.Add a flag/method for use or not weak references.
$eventsManager = new Phalcon\Events\Manager();
$myListener = new MyListener();
// flag
$eventManager->attach('somecomponent', $myListener, $priority, $isWeak);
// method
$eventManager->attachUsingWeakRef('somecomponent', $myListener, $priority);
3.Use weakref-php-extension and add possibility register Event-handler as "WeakRef" object.
So when event fired then will checked that event-handler is WeakRef object or not.
If is WeakRef object then will check whether the object referenced still exists and if exists - fire!
If is not WeakRef object then standart fire.
$eventsManager = new Phalcon\Events\Manager();
$myListener = new MyListener();
$eventManager->attach('somecomponent', new WeakRef($myListener));
Avaliable php-extension for Weak References: http://www.php.net/manual/en/book.weakref.php
Zend Framework 2 uses WeakRef extension.