概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:51:21 | 97 次阅读 | 评论: 0 | 来源: 网络整理

The base Event class provided by the EventDispatcher component is deliberately sparse to allow the creation of API specific event objects by inheritance using OOP. This allows for elegant and readable code in complex applications.

The GenericEvent is available for convenience for those who wish to use just one event object throughout their application. It is suitable for most purposes straight out of the box, because it follows the standard observer pattern where the event object encapsulates an event ‘subject’, but has the addition of optional extra arguments.

GenericEvent has a simple API in addition to the base class Event

The GenericEvent also implements ArrayAccess on the event arguments which makes it very convenient to pass extra arguments regarding the event subject.

The following examples show use-cases to give a general idea of the flexibility. The examples assume event listeners have been added to the dispatcher.

Simply passing a subject:

use SymfonyComponentEventDispatcherGenericEvent;

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

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

Passing and processing arguments using the ArrayAccess API to access the event arguments:

use SymfonyComponentEventDispatcherGenericEvent;

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

echo $event['counter'];

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

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

Filtering data:

use SymfonyComponentEventDispatcherGenericEvent;

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

echo $event['data'];

class FooListener
{
    public function filter(GenericEvent $event)
    {
        $event['data'] = strtolower($event['data']);
    }
}
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务