PHP code example of fastd / event

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

    

fastd / event example snippets




class UserLoginSuccessEvent
{
    public function __construct(
        public int $userId,
        public string $ipAddress,
        public string $loginTime
    ) {
    }
}



class UserLoginLogListener
{
    public function __invoke(UserLoginSuccessEvent $event): void
    {
        echo "【登录日志监听器】已记录登录日志:用户 {$event->userId} 于 {$event->loginTime} 从 IP {$event->ipAddress} 登录成功\n";
    }
}

class UserLoginNotificationListener
{
    public function __invoke(UserLoginSuccessEvent $event): void
    {
        echo "【登录通知监听器】已发送通知:用户 {$event->userId},您已成功登录系统(登录 IP:{$event->ipAddress},登录时间:{$event->loginTime})\n";
    }
}



astD\Event\EventDispatcher;
use FastD\Event\ListenerProvider;
use FastD\Event\EventPriority;

// 创建监听器提供者
$provider = new ListenerProvider();

// 添加监听器(使用默认优先级)
$provider->addListener(UserLoginSuccessEvent::class, new UserLoginLogListener());

// 添加高优先级监听器
$provider->addListener(UserLoginSuccessEvent::class, new UserLoginNotificationListener(), EventPriority::HIGH);

// 创建事件调度器
$dispatcher = new EventDispatcher($provider);

// 创建并分发事件
$event = new UserLoginSuccessEvent(1001, '127.0.0.1', date('Y-m-d H:i:s'));
$result = $dispatcher->dispatch($event);

echo "\n事件处理完成,用户 ID:{$result->userId}\n";

use FastD\Event\EventPriority;

// 使用预定义优先级
$provider->addListener(MyEvent::class, $listener, EventPriority::HIGHEST);  // 最高优先级
$provider->addListener(MyEvent::class, $listener, EventPriority::HIGH);     // 高优先级
$provider->addListener(MyEvent::class, $listener, EventPriority::NORMAL);   // 普通优先级
$provider->addListener(MyEvent::class, $listener, EventPriority::LOW);      // 低优先级
$provider->addListener(MyEvent::class, $listener, EventPriority::LOWEST);   // 最低优先级

// 或使用自定义数值(数值越大优先级越高)
$provider->addListener(MyEvent::class, $listener, 1000);  // 高优先级
$provider->addListener(MyEvent::class, $listener, -100);  // 低优先级

interface BaseEventInterface {}

class BaseEvent implements BaseEventInterface {}

class ChildEvent extends BaseEvent {}

// 这个监听器会同时处理 BaseEvent 和 ChildEvent
$provider->addListener(BaseEvent::class, $baseListener);
$provider->addListener(BaseEventInterface::class, $interfaceListener);

// 分发子类事件时,父类和接口的监听器也会被触发
$dispatcher->dispatch(new ChildEvent());

use FastD\Event\Event;

class MyStoppableEvent extends Event
{
    public function __construct(private string $data)
    {
        parent::__construct();
    }

    public function getData(): string
    {
        return $this->data;
    }
}

// 在某个监听器中停止事件传播
class StopEventListener
{
    public function __invoke(MyStoppableEvent $event): void
    {
        if ($event->getData() === 'stop') {
            $event->stopPropagation();
        }
    }
}

use FastD\Event\EventListenerInterface;

class MyEventListener implements EventListenerInterface
{
    public function handle(object $event): void
    {
        if ($event instanceof MyEvent) {
            // 处理事件逻辑
            echo "Processing event: " . $event->getData();
        }
    }
    
    public function __invoke(object $event): void
    {
        $this->handle($event);
    }
}

// 使用监听器
$provider->addListener(MyEvent::class, new MyEventListener());

use FastD\Event\Event;

class MyEvent extends Event
{
    public string $data;
    
    public function __construct(string $data)
    {
        parent::__construct();
        $this->data = $data;
    }
}

// 添加会抛出异常的监听器
$provider->addListener(MyEvent::class, function($event) {
    throw new \RuntimeException('Something went wrong');
});

$myEvent = new MyEvent('test');
$result = $dispatcher->dispatch($myEvent);

// 检查事件中是否有异常
if (!empty($result->getExceptions())) {
    $exceptions = $result->getExceptions();
    foreach ($exceptions as $listenerClass => $exception) {
        echo "Caught exception from " . $listenerClass . ": " . $exception->getMessage();
    }
}

use FastD\Event\CoroutineEventDispatcher;
use FastD\Event\CoroutineSampleListener;

// 创建协程调度器
$coroutineDispatcher = new CoroutineEventDispatcher($provider);

// 使用协程监听器
$coroutineListener = new CoroutineSampleListener();
$provider->addListener(MyEvent::class, $coroutineListener);

// 同步运行协程调度
$result = $coroutineDispatcher->runDispatch($event);

// 或获取生成器手动控制
$generator = $coroutineDispatcher->getGenerator($event);
foreach ($generator as $value) {
    // 处理生成的值
}