symbiotic/event

Slim, PSR-14 事件管理轻量级微实现

1.4.0 2022-09-11 15:21 UTC

This package is auto-updated.

Last update: 2024-09-12 04:16:54 UTC


README

README.RU.md 俄语描述

特性

  • 兼容 PSR-14
  • 简单轻量(2.5 Kb)
  • 接受类名作为订阅者
  • 可以与您的 DI 容器共享
  • 没有私有属性和方法

安装

composer require symbiotic/event 

用法

基本用法
use Symbiotic\Event\ListenerProvider;
use Symbiotic\Event\EventDispatcher;

$listeners  = new ListenerProvider();
$dispatcher = new EventDispatcher($listeners);

$listeners->add(\MyEvents\FirstEvent::class, function(\MyEvents\FirstEvent $event) {
    // handle event
});

// Run event

$event = new \MyEvents\FirstEvent();
$dispatcher->dispatch(new \MyEvents\FirstEvent());
使用您的手枪订阅者

您可以自己包装订阅者并处理事件,例如,您可以传递事件到一个类或通过您的 DI 容器执行它。

use Symbiotic\Event\ListenerProvider;
use Symbiotic\Event\EventDispatcher;

/**
 * @var \Closure|string $listener  you can wrap the subscribers yourself and handle the event,
 * for example, you can pass the event to a class or execute it through your DI container
 **/
$listener_wrapper = function($listener) {
    return function(object $event) use ($listener) {
            // if classname
            if(is_string($listener) && class_exists($listener)) {
                $listener = new $listener();
                return $listener->handle($event);
            } elseif(is_callable($listener)) {
                return $listener($event);
            }
    };
};

$listeners  = new ListenerProvider($listener_wrapper);
$dispatcher = new EventDispatcher($listeners);
// classname handler
$listeners->add(\MyEvents\FirstEvent::class, \MyEvents\Handlers\FirstHandler::class);
// callable handler
$listeners->add(\MyEvents\FirstEvent::class, function(\MyEvents\FirstEvent $event) {
    // handle event
});

// Run event

$event = new \MyEvents\FirstEvent();
$dispatcher->dispatch(new \MyEvents\FirstEvent());

可停止的事件

如果事件实现了 \Psr\EventDispatcher\StoppableEventInterface 接口,则可以停止

class StopEvent implements Psr\EventDispatcher\StoppableEventInterface
{
    // Your logic for stopping
    public function isPropagationStopped(): bool
    {
        return true;
    }
}

此行为对于需要监听器停止处理的事件可能很有用。