Simple event dispatching library for PHP
The preferred way to install this extension is through Composer.
Either run
composer require yarcode/simple-events
or add
"yarcode/simple-events": "*"
to the require section of your composer.json
Attach \YarCode\Events\EventEmitterTrait
to your class to make it EventEmitter
class MyClass {
use \YarCode\Events\EventEmitterTrait;
...
}
$emitter = new MyClass();
Or create an instance of \YarCode\Events\EventEmitter
.
$emitter = new \YarCode\Events\EventEmitter();
You can add callable
listener for any string event name.
$emitter->addListener('TestEvent', function (\YarCode\Events\Event $event) {
echo "{$event->name} was emitted";
});
$emitter->addListener('TestEvent', function (\YarCode\Events\Event $event) {
echo "{$event->name} was emitted one more time";
});
You can emit named event with default event object.
$emitter->emit('TestEvent');
// TestEvent was emitted
// TestEvent was emitted one more time
Or you can pass \YarCode\Events\Event
object to the listeners.
$event = new \YarCode\Events\Event();
$event->payload['key'] = 'value';
$emitter->emit('TestEvent', $event);
// TestEvent was emitted
// TestEvent was emitted one more time
You could pass any data as event payload. It would be passed as a first parameter to a listener callable.
$data = ['foo', 'bar'];
$emitter->emit('MixedDataEvent', $data);
You can remove one concrete listener.
$callback = function (\YarCode\Events\Event $event) {
echo "{$event->name} was emitted third time";
});
$emitter->addListener('TestEvent', $callback);
$emitter->removeListener('TestEvent', $callback);
Or remove all the listeners for the event.
$emitter->removeAllListeners('TestEvent');
Or remove all the listeners for all events.
$emitter->removeAllListeners();
Set the $event->handled
property to true
to stop the further listeners execution.
$emitter->addListener('TestEvent', function (\YarCode\Events\Event $event) {
$event->handled = true;
});
$emitter->addListener('TestEvent', function (\YarCode\Events\Event $event) {
echo "This callback for {$event->name} would never run";
});
$emitter->emit('TestEvent');
Emitter object is being passed as a second parameter to a listener.
$emitter->addListener('TestEmitterAccessEvent', function ($data, $emitter) {
echo "Hello";
$emitter->emit('TestEmitterAccessEvent2', $data);
});
$emitter->addListener('TestEmitterAccessEvent2', function ($data) {
echo " World";
});
$emitter->emit('TestEmitterAccessEvent');
// Hello World
MIT