您如何接口事件调度程序



我正在尝试连接事件调度程序,并有一段时间提出解决方案。到目前为止,我有以下简单接口:

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

现在,我正在尝试使用Symfony的EventDispatcher实现它。问题是Symfony的dispatch方法期望第二个参数实现其Event抽象类。好..所以我现在必须想出包装班吗?

use SymfonyComponentEventDispatcherEvent;
class SymfonyEvent extends Event
{
    private $data;
    public function __construct($data)
    {
        $this->data = $data;
    }
    public function getData()
    {
        return $this->data;
    }
} 

这是实现的第一个通过

use SymfonyComponentEventDispatcherEventDispatcher 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);
    }
} 

我该如何写不可知论事件听众?

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/

相关内容

  • 没有找到相关文章

最新更新