Created
November 9, 2012 17:03
-
-
Save davidwindell/4046877 to your computer and use it in GitHub Desktop.
ZF2 Doctrine Flush Listener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
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?