我有一个Symfony 2的控制台应用程序,该脚本在cron(终端)上运行。但是,在\ Doctrine \ DBAL \ DBALException之后,脚本抛出N \ Doctrine \ ORM \ ORMException并显示消息" EntityManager已关闭。"。
这是部分脚本:
try {
$this->getDoctrine()->getConnection()->beginTransaction();
// ...
$manager = $this->getDoctrine()->getManager();
$entity = new Post();
$entity
->setAuthor($author)
->setTitle($title)
->setContent($content)
;
$manager->persist($entity);
$manager->flush();
$this->getDoctrine()->getConnection()->commit();
return $entity->getId();
} catch (\Doctrine\DBAL\DBALException $e) {
$this->getDoctrine()->resetManager();
$output->writeln(sprintf(
'<error>[!] %s (%s) the post could not be created "%s"</error>',
get_class($e),
date('Y-m-d H:i:s'),
$e->getMessage()
));
return false;
} catch (\Exception $e) {
$this->getDoctrine()->getConnection()->rollback();
$output->writeln(sprintf(
'<error>[!] %s (%s) the post could not be created "%s"</error>',
get_class($e),
date('Y-m-d H:i:s'),
$e->getMessage()
));
return false;
}
如何解决?
答案 0 :(得分:6)
您可以像这样手动重置您的实体管理员:
//...
} catch (\Doctrine\DBAL\DBALException $e) {
$manager = $this->getDoctrine()->getManager();
if (!$manager->isOpen()) {
$manager = $manager->create(
$manager->getConnection(),
$manager->getConfiguration()
);
}
$output->writeln(sprintf(
'<error>[!] %s (%s) the post could not be created "%s"</error>',
get_class($e),
date('Y-m-d H:i:s'),
$e->getMessage()
));
return false;
}
//...
答案 1 :(得分:-1)
如果您在项目中使用PSR-15和PHP-DI,请尝试以下中间件:
https://github.com/autorusltd/doctrine-persistent-entity-manager-middleware
您可以像这样使用它:
use Arus\Middleware\DoctrinePersistentEntityManagerMiddleware;
$requestHandler->add(new DoctrinePersistentEntityManagerMiddleware($container));
$requestHandler->handle($request);