yarcode / simple-events
Simple event dispatching library for PHP
Installs: 1 688
Dependents: 1
Suggesters: 0
Security: 0
Stars: 2
Watchers: 2
Forks: 1
Open Issues: 0
Requires
- php: ^7
Requires (Dev)
- phpunit/phpunit: ~6
This package is not auto-updated.
Last update: 2024-11-09 20:01:53 UTC
README
Simple event dispatching library for PHP
Installation
Composer
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
Usage
Via EventEmitterTrait
Attach \YarCode\Events\EventEmitterTrait
to your class to make it EventEmitter
class MyClass { use \YarCode\Events\EventEmitterTrait; ... } $emitter = new MyClass();
Standalone EventEmitter
Or create an instance of \YarCode\Events\EventEmitter
.
$emitter = new \YarCode\Events\EventEmitter();
Adding listeners
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";
});
Emitting events
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);
Removing listeners
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();
Breaking the execution
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');
Accessing the emitter from the listener
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
License
MIT