PHP code example of pagon / eventemitter

1. Go to this page and download the library: Download pagon/eventemitter 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/ */

    

pagon / eventemitter example snippets


$event = new EventEmitter();

// 绑定事件
$event->on('new', function () {
    echo 'A new client is coming' . PHP_EOL;
});

// 触发
$event->emit('new');

$event = new EventEmitter();

// 绑定单次事件
$event->once('new', function () {
    echo 'A new client is coming' . PHP_EOL;
});

// 触发
$event->emit('new');

// 不触发
$event->emit('new');

$event = new EventEmitter();

// 绑定2次事件
$event->many('new', 2, function () {
    echo 'A new client is coming' . PHP_EOL;
});

$event->emit('new'); // 触发
$event->emit('new'); // 触发
$event->emit('new'); // 不触发

$event = new EventEmitter();

// 绑定模糊事件
$event->on('news.*', function($id){
    echo $id . ' is comming..., ID is ';
});

$event->emit('news.1');
$event->emit('news.2');
$event->emit('news.3');

$event = new EventEmitter();

// 闭包回调
$operator = function () {
    echo 'A new client is coming' . PHP_EOL;
};

$event->on('new', $operator);

$event->emit('new');           // 触发

$event->off('new', $operator); // 解除绑定
$event->emit('new');           // 不触发

$event = new EventEmitter();

$event->on('new', function () {
    echo 'A new client is coming' . PHP_EOL;
});

$event->removeAllListeners('new');

$event = new EventEmitter();

$event->on('new', function () {
    echo 'A new client is coming' . PHP_EOL;
});

$event->on('close', function () {
    echo 'The client has closed' . PHP_EOL;
});

$event->removeAllListeners();

class MyClass extends EventEmitter {
}

$my = new MyClass;
$my->on('create', function($data){
    $db->save($data);
});

// 注册事件
Event::on('save', function ($arg) {
    echo '1 saved: ' . $arg . PHP_EOL;
});

// 触发事件
Event::emit('save', 'test');

$emitter = new EventEmitter();
// 更换触发器
Event::emitter($emitter);

// 绑定事件
$event->on('save', function ($arg) {
    echo '1 saved: ' . $arg . PHP_EOL;
});

// 触发save
$event->emit('save', 'test');

// 效果同上
$emitter->emit('save', 'test');