pradosoft / prado

Prado - Component Framework for PHP
Other
187 stars 70 forks source link

#939 TEventHandler for event handlers with specific data #942

Closed belisoful closed 1 year ago

belisoful commented 1 year ago

The new TEventHandler attaches specific data to a managed event handler. This is used by wrapping your Event Handler calllable with new TEventHandler(..., $data) and specify your $data. The handler will then receive the $data as a 3rd parameter after $sender and $param.

here is an example of its being used:

$handler = new TEventHandler([$object, 'myHandler'], ['key' => 'data']);
$handler($sender, $param); // <- invokable
$component->attachEventHandler('onMyEvent', $handler, $priority);

// In the $object class when $component::onMyEvent is raised:
public function myHandler(object $sender, mixed $param, mixed $data = null): mixed
{
    // $data === ['key' => 'data']
    //       ....
}

Callable handler objects are converted to WeakReference. The exception are Closure and IWeakRetainable as they may be the only instance in the application. TEventHandler implements IWeakRetainable.

Yii2 has had data associated with event handlers for a bit, but their implementation is just hacking their base component with an extra variable. In this implementation, The TEventHandler is an object rather than just embedded with the handler. The TEventHandler can be passed around, it's data changed dynamically after the event handler is attached.

This also allows for TEventHandler Nesting where the data (if its an array) of nested TEventHandlers can combine. The chlldren take precedence over the parents, similar to PHP class structure.