0

我正在尝试与事件调度程序交互,并想出一个解决方案。到目前为止,我有以下简单的界面:

interface EventDispatcherInterface
{
    public function fire($name, $data);
}

现在我正在尝试使用 symfony 的EventDispatcher. 问题是 symfony 的dispatch方法需要第二个参数来实现它的Event抽象类。好的..所以现在我必须想出一个包装类?

use Symfony\Component\EventDispatcher\Event;

class SymfonyEvent extends Event
{
    private $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }
} 

这是实现的第一遍

use Symfony\Component\EventDispatcher\EventDispatcher as SymfonyEventDispatcher;

class SymfonyDispatcher implements EventDispatcherInterface
{
    protected $dispatcher;

    public function __construct(SymfonyEventDispatcher $dispatcher = null)
    {
        $this->dispatcher = $dispatcher ? : new SymfonyEventDispatcher;
    }

    public function fire($name, $data)
    {
        $event = new SymfonyEvent($data);

        $this->dispatcher->dispatch($name, $event);
    }
} 

我该如何编写不可知的事件侦听器?

4

1 回答 1

1
class SymfonyEventDispatcher implements EventDispatcher
{

    private $eventDispatcher;

    public function __construct(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    public function dispatch(Event $event)
    {
        $listeners = $this->eventDispatcher->getListeners($event->getName());

        foreach ($listeners as $listener) {
            call_user_func($listener, $event);
        }
    }
}

来自 Matthais Noback 的关于您的问题的精彩博客:http: //php-and-symfony.matthiasnoback.nl/2014/08/symfony2-decoupling-your-event-system/

于 2014-09-25T01:35:57.720 回答