跳到内容

通用事件对象

编辑此页

EventDispatcher 组件提供的基础 Event 类被刻意设计得非常简洁,以便通过 OOP 继承创建特定于 API 的事件对象。这使得在复杂的应用程序中编写出优雅且可读的代码成为可能。

GenericEvent 的存在是为了方便那些希望在整个应用程序中只使用一个事件对象的人。它开箱即用,适用于大多数目的,因为它遵循标准的观察者模式,其中事件对象封装了一个事件“主题”,但还添加了可选的额外参数。

除了基础 Event 类之外,GenericEvent 还添加了一些方法

GenericEvent 还针对事件参数实现了 ArrayAccess 接口,这使得传递关于事件主题的额外参数非常方便。

以下示例展示了用例,以便对灵活性有一个大致的了解。这些示例假设事件监听器已被添加到调度器中。

传递主题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
use Symfony\Component\EventDispatcher\GenericEvent;

$event = new GenericEvent($subject);
$dispatcher->dispatch($event, 'foo');

class FooListener
{
    public function handler(GenericEvent $event): void
    {
        if ($event->getSubject() instanceof Foo) {
            // ...
        }
    }
}

使用 ArrayAccess API 传递和处理参数以访问事件参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\EventDispatcher\GenericEvent;

$event = new GenericEvent(
    $subject,
    ['type' => 'foo', 'counter' => 0]
);
$dispatcher->dispatch($event, 'foo');

class FooListener
{
    public function handler(GenericEvent $event): void
    {
        if (isset($event['type']) && 'foo' === $event['type']) {
            // ... do something
        }

        $event['counter']++;
    }
}

过滤数据

1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\EventDispatcher\GenericEvent;

$event = new GenericEvent($subject, ['data' => 'Foo']);
$dispatcher->dispatch($event, 'foo');

class FooListener
{
    public function filter(GenericEvent $event): void
    {
        $event['data'] = strtolower($event['data']);
    }
}
这项工作,包括代码示例,均在 Creative Commons BY-SA 3.0 许可下获得许可。
目录
    版本