gobline/mediator

v3.0.0 2015-12-03 09:18 UTC

This package is auto-updated.

Last update: 2024-09-12 19:42:52 UTC


README

中介组件允许您的应用组件通过分发和监听事件进行相互通信。它实现了中介行为设计模式。

创建分发器

use Gobline\Mediator\EventDispatcher;

$dispatcher = new EventDispatcher();

添加事件订阅者

use Gobline\Mediator\EventSubscriberInterface;

class FooSubscriber implements EventSubscriberInterface
{
    public function onFooEvent()
    {
        // ... do something
    }

    public function getSubscribedEvents()
    {
        return ['fooEvent' => 'onFooEvent'];
    }
}

$subscriber = new FooSubscriber();
$dispatcher->addSubscriber($subscriber);

添加事件监听器

事件监听器类似于事件订阅者。唯一的区别是事件监听器不需要实现 EventSubscriberInterface 接口并提供它所监听的事件。相反,您可以在类外部指定它所监听的事件。使用事件监听器来替代上面示例的方法将是

class FooListener
{
    public function onFooEvent()
    {
        // ... do something
    }
}

$listener = new FooListener();
$dispatcher->addListener($listener, ['fooEvent' => 'onFooEvent']);

懒加载监听器

您可以为监听器添加一个闭包,该闭包将在事件分发时懒加载监听器实例。这允许监听器仅在它监听的事件被分发时才被实例化。

$dispatcher->addListener(
    function() { return new FooListener(); },
    ['fooEvent' => 'onFooEvent']);

分发事件

$dispatcher->dispatch('fooEvent');

传递事件数据

$dispatcher->dispatch('fooEvent', ['foo' => 'bar']);

class FooListener
{
    public function onFooEvent(array $data)
    {
        // ... do something with $data['foo']
    }
}

安装

您可以使用依赖管理工具 Composer 安装中介组件。运行 require 命令以解析和下载依赖项

composer require gobline/mediator