small/swoole-events

1.0.4 2024-02-06 10:08 UTC

This package is auto-updated.

Last update: 2024-09-06 11:36:44 UTC


README

small-events 利用 OpenSwoole 异步框架提供 PSR 事件调度器

            

事件

事件是所有扩展 AbstractEvent 的类。

为了允许多线程数据共享,事件数据必须通过构造函数中的 setData 方法定义。

class SimpleEvent extends AbstractEvent
{

    public function __construct(int $data1, int $data2)
    {

        $this->setId(1);
        $this->data = new Collection(['data1' => $data1, 'data2' => $data2]);
        $this->createDataTable();
        $this->setData('data1', $data1);
        $this->setData('data2', $data2);

    }

    public function getData($field): mixed
    {

        $data = $this->gatherResult();
        return $data[$field];

    }

    public function jsonSerialize(): mixed
    {

        return $this->gatherResult();;

    }

}

事件监听器

事件监听器是一个处理事件并执行某些任务或更新事件数据的类。

它必须实现 ListenerInterface 接口,这意味着您至少需要实现以下内容:

  • getPriority : 返回监听器的优先级
  • getHandleableEvents : 返回监听器可以处理的的事件类型(类)列表
  • handle : 处理一个事件

例如,以下是一个可以处理前面 SimpleEvent 的监听器

class AppListener implements ListenerInterface
{

    public static function getPriority(): string
    {
        return Priority::getPriorityByName(Priority::APP_EXTERNAL_LOW);
    }

    public static function getHandleableEvents(): array
    {

        return [SimpleEvent::class];

    }

    /**
     * @param SimpleEvent $event
     * @return ListenerInterface
     * @throws \Exception
     */
    public function handle(AbstractEvent $event): ListenerInterface
    {

        $event->setData('data1', 1);
        $event->setData('data2', $event->getData('data2') + 1);

        return $this;

    }

}

事件处理监听器的优先级在 Priority 类中定义

\Small\SwooleEvents\Listener\Priority::KERNEL_HIGH;
\Small\SwooleEvents\Listener\Priority::KERNEL_MIDDLE;
\Small\SwooleEvents\Listener\Priority::KERNEL_LOW;
\Small\SwooleEvents\Listener\Priority::APP_INTERNAL_HIGH;
\Small\SwooleEvents\Listener\Priority::APP_INTERNAL_MIDDLE;
\Small\SwooleEvents\Listener\Priority::APP_INTERNAL_LOW;
\Small\SwooleEvents\Listener\Priority::APP_EXTERNAL_HIGH;
\Small\SwooleEvents\Listener\Priority::APP_EXTERNAL_MIDDLE;
\Small\SwooleEvents\Listener\Priority::APP_EXTERNAL_LOW;

执行将从 KERNEL(第一个)到 APP_EXTERNAL(最后一个),从 HIGH 到 LOW 进行。

事件调度

创建事件提供者并注册监听器

$listenerProvider = new ListenerProvider();
$listenerProvider->addListener(new KernelSimpleEventListener());
$listenerProvider->addListener(new AppSimpleEventListener());

创建事件调度器

$event = new EventDispatcher(
    $listenerProvider,
    $this->container, // The psr container of your favorite framework
);

创建事件并将它们调度

$listenerProvider->dispatch(new SimpleEvent(0, 2));

执行顺序

事件按优先级批量提交给监听器,从 KERNEL 到 APP_EXTERNAL。

每个批处理中的事件处理都是异步执行的。