Skip to content

Instantly share code, notes, and snippets.

@davidwindell
Created November 9, 2012 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save davidwindell/4046877 to your computer and use it in GitHub Desktop.
Save davidwindell/4046877 to your computer and use it in GitHub Desktop.
ZF2 Doctrine Flush Listener
<?php
namespace Application\Listener\Doctrine;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\EntityManager;
use Zend\EventManager\EventInterface;
use Zend\Mvc\MvcEvent;
class FlushEntities
{
public static $requiresFlush = false;
const ERROR_FLUSH = 'error-flush';
public static function flush(EventInterface $e)
{
if ($e->getParam('delay') == true) {
self::$requiresFlush = true;
return;
}
if ($e->getTarget() instanceof EntityManager) {
$em = $e->getTarget();
if (self::$requiresFlush) {
$em->flush();
self::$requiresFlush = false;
} else {
$em->flush($e->getParam('entity'));
}
return;
}
if (!self::$requiresFlush) {
return;
}
if (!$e instanceof MvcEvent) {
return;
}
try {
$e->getApplication()->getServiceManager()->get('EntityManager')->flush();
self::$requiresFlush = false;
} catch (DBALException $ex) {
$e->setError(self::ERROR_FLUSH)
->setParam('exception', $ex);
$e->getApplication()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $e);
}
}
}
@davidwindell
Copy link
Author

To use this, attach like so;

$app->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, array('Application\Listener\Doctrine\FlushEntities', 'flush'), -1);

and

$events->attach(__NAMESPACE__, 'flush', array('Application\Listener\Doctrine\FlushEntities', 'flush'));

Any thoughts, improvements?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment