php - Symfony2 中的设计模式 : is EventDispatcher a Mediator or Event Aggregator?

标签 php symfony design-patterns eventaggregator mediator

来自 Symfony2 的 EventDispatcher 组件文档:

The Symfony2 EventDispatcher component implements the Mediator pattern in a simple and effective way to make all these things possible and to make your projects truly extensible.

我一直在阅读 Event Aggregator和中介者模式及其 differences .在我看来,Event Aggregator 是 Mediator 的一个特例,它使用事件来促进通信,并且内部没有任何业务逻辑。另一方面,调解器更通用,可以让一些业务逻辑决定是否应该通过某些通信。

于是我查看了Symfony2的EventDispatcher或TraceableEventDispatcher的源码,发现唯一可能改变通信的逻辑是检查事件传播是否已经停止,如下:

protected function doDispatch($listeners, $eventName, Event $event)
{
    foreach ($listeners as $listener) {
        call_user_func($listener, $event, $eventName, $this);
        if ($event->isPropagationStopped()) {
            break;
        }
    }
}

这就是为什么 Symfony2 中的 EventDispatcher 实现了 Mediator 模式而不是 Event Aggregator 模式?如果检查 isPropagationStopped 的逻辑从 EventDispatcher 中移出(例如,移到事件监听器中),那么这将实现 Event Aggregator?

最佳答案

Event Aggregator 类似于 Observer 模式,Subject 只是通知 Observer 对象有变化,无论是什么类型的事件都需要更新。

Symfony2 的 EventDispatcher 实现了 Mediator 模式,因为它就像一个路由器,决定什么事件将由可以订阅多个事件的监听器触发。如您所见,即使删除了 isPropagationStopped 部分,EventDispatcher 仍然需要事件名称来确定触发哪个事件。

安东尼费拉拉有一个伟大的 blog post讨论这个问题

关于php - Symfony2 中的设计模式 : is EventDispatcher a Mediator or Event Aggregator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641300/

相关文章:

javascript - 使用 Laravel 将 HTML 生成为 PDF,并将生成的 PDF 上传到数据库?

php - 在我向表中添加新列后代码停止工作

php - 如何在 cakephp 3.x 中执行自定义查询

c# - 条件生成器方法链接 Fluent 接口(interface)

java - 可插入的错误处理策略

php - zend db 查询获取不需要的列

php - 将 Symfony 表单字段包装在 Twig 的 div 中

php - 带有服务器端 PHP 模板的 ReactJS?

php - Symfony2 : remember me token is not set

networking - 微服务扩展/插件架构