PHP code example of yarcode / simple-events

1. Go to this page and download the library: Download yarcode/simple-events library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yarcode / simple-events example snippets


class MyClass {
    use \YarCode\Events\EventEmitterTrait;
    ...
}
$emitter = new MyClass();

$emitter = new \YarCode\Events\EventEmitter();

$emitter->emit('TestEvent');
// TestEvent was emitted
// TestEvent was emitted one more time

$event = new \YarCode\Events\Event();
$event->payload['key'] = 'value';
$emitter->emit('TestEvent', $event);
// TestEvent was emitted
// TestEvent was emitted one more time

$data = ['foo', 'bar'];
$emitter->emit('MixedDataEvent', $data);

$emitter->removeAllListeners('TestEvent');

$emitter->removeAllListeners();

$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->addListener('TestEmitterAccessEvent', function ($data, $emitter) {
    echo "Hello"; 
    $emitter->emit('TestEmitterAccessEvent2', $data);
});
$emitter->addListener('TestEmitterAccessEvent2', function ($data) {
    echo " World";
});
$emitter->emit('TestEmitterAccessEvent');
// Hello World

$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";
});

$callback = function (\YarCode\Events\Event $event) {
    echo "{$event->name} was emitted third time";
});
$emitter->addListener('TestEvent', $callback);
$emitter->removeListener('TestEvent', $callback);