Skip to content

Instantly share code, notes, and snippets.

@kcassam
Created January 30, 2017 08:35
Show Gist options
  • Save kcassam/7448b8ec683a8c691f090c88a52118e3 to your computer and use it in GitHub Desktop.
Save kcassam/7448b8ec683a8c691f090c88a52118e3 to your computer and use it in GitHub Desktop.
Doctrine Utils
<?php
//stackoverflow.com/questions/13069315/how-to-retry-transaction-after-a-deadlock-using-doctrine
//cannot retry : stackoverflow.com/questions/13069315/how-to-retry-transaction-after-a-deadlock-using-doctrine#comment31758644_13150683
//codedump.io/share/rjB45oiwtqwo/1/doctrine2-the-entitymanager-is-closed-how-to-reset-entity-manager-in-symfony2
namespace Headoo\UtilityBundle\Helper;
use Doctrine\DBAL\Exception\RetryableException;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
class DoctrineHelper
{
// Entity manager;
private $em;
private $logger;
/* @return void */
public function superflush(EntityManagerInterface $em, LoggerInterface $logger = null): void {
$this->em = $em;
$this->logger = $logger;
try {
$this->em->flush();
} catch (\Exception $e) {
if ($this->logger) {
$msg = '### Catched Exception ### \n ### Message ### \n'.$e->getMessage().'\n### Trace ### \n'.$e->getTraceAsString();
$this->container->get('logger')->critical($msg);
}
$this->reset();
}
}
private function reset(): void {
// reset entity manager
if (!$this->em->isOpen()) {
$this->em = $this->em->create(
$this->em->getConnection(),
$this->em->getConfiguration()
);
}
}
/*
* Since doctrine 2.6, you cannot retry a flush when an exception had appeared
* because the entity manager is closed and all entities detach, even with a RetryableException.
* This function won't work, bescause if there is an Exception, the em is closed.
* I keep it to warn you if you have the same idea.
private retryflush() {
$retry = 0;
while ($retry < 3) {
try {
$this->em->flush();
return;
} catch (RetryableException $e) {
if ($retry >= 2) {
throw $e;
}
sleep(1);
$this->reset();
$retry++;
}
}
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment