Skip to content

Instantly share code, notes, and snippets.

@xphere
Created December 2, 2013 10:51
Show Gist options
  • Select an option

  • Save xphere/7747860 to your computer and use it in GitHub Desktop.

Select an option

Save xphere/7747860 to your computer and use it in GitHub Desktop.
Async events
<?php
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\Event;
trait AsyncDispatcherTrait
{
/** @var EventDispatcherInterface */
protected $dispatcher;
/** @var null|Event[] */
protected $pendingEvents = null;
public function setDispatcher(EventDispatcherInterface $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function notifyAsync()
{
$events = $this->pendingEvents;
$this->pendingEvents = [];
foreach ($events as $type => $event) {
$this->dispatcher->dispatch($type, $event);
}
}
protected function async($type, Event $event)
{
if (null === $this->pendingEvents) {
$this->pendingEvents = [];
$this->dispatcher->addListener(KernelEvents::TERMINATE, array($this, 'notifyAsync'));
}
$this->pendingEvents[$type][] = $event;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment