我正在尝试与事件调度程序进行交互,并且有一段时间想出一个解决方案。到目前为止,我有以下简单的界面:
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);
}
}
我如何编写不可知的事件监听器?
答案 0 :(得分: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/