Skip to content

Instantly share code, notes, and snippets.

@mdjaman
Forked from davidwindell/FlushEntities.php
Created July 30, 2013 12:11
Show Gist options
  • Save mdjaman/6112391 to your computer and use it in GitHub Desktop.
Save mdjaman/6112391 to your computer and use it in GitHub Desktop.
<?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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment