1. Go to this page and download the library: Download raylin666/event-dispatcher 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/ */
raylin666 / event-dispatcher example snippets
Dispatcher = new \Raylin666\EventDispatcher\Dispatcher;
$listenerProvider = new \Raylin666\EventDispatcher\ListenerProvider();
$eventDispatcher($listenerProvider);
$listenerProvider->addListener('lang', function () {
echo "golang \n";
});
$listenerProvider->addListener('lang', function () {
echo "php \n";
}, 2);
$listenerProvider->addListener('lang', function () {
echo "java \n";
});
class LangEvent extends \Raylin666\EventDispatcher\Event
{
public function getEventAccessor(): string
{
// TODO: Implement getEventAccessor() method.
return 'lang';
}
public function isPropagationStopped(): bool
{
// 事件是否需要执行, 为 true 时 不执行该事件绑定的所有监听
return false;
}
}
$eventDispatcher->dispatch(new LangEvent());
// 输出
/*
php
java
golang
*/
### 订阅器 [订阅器(Subscriber)实际上是对 ListenerProvider::addListener 的一种装饰]
/*
利用 ListenerProvider::addListener 添加事件和监听器的关系,这种方式比较过程化,
也无法体现出一组事件之间的关系,所以在实践中往往会提出“订阅器”的概念
*/
class OnStartEvent extends \Raylin666\EventDispatcher\Event
{
public function getEventAccessor(): string
{
// TODO: Implement getEventAccessor() method.
return 'onStart';
}
public function isPropagationStopped(): bool
{
// 事件是否需要执行, 为 true 时 不执行该事件绑定的所有监听
return false;
}
}
class OnStartSubscriber implements \Raylin666\Contract\SubscriberInterface
{
public function subscribe(Closure $subscriber)
{
// TODO: Implement subscribe() method.
$subscriber(
'onStart',
'onStartListener',
'onStartTwoListener'
);
}
public function onStartListener()
{
echo "我是开始监听事件 1 \n";
}
public function onStartTwoListener(OnStartEvent $event)
{
return call_user_func_array(function (OnStartEvent $event, $writeString) {
var_dump($event->getEventAccessor());
var_dump($writeString);
}, [$event, "我是开始监听事件 2"]);
}
}
$listenerProvider->addSubscriber(new OnStartSubscriber());
$eventDispatcher->dispatch(new OnStartEvent());
// 输出
/*
我是开始监听事件 1
string(7) "onStart"
string(26) "我是开始监听事件 2"
*/
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.