重置实体管理器的最佳方法

时间:2018-06-21 14:53:22

标签: php symfony

当我遇到PdoException时,最好重置理论实体管理器吗?

在foreach循环中,我需要保存获得的最大实体。如果一个实体失败,我想发送电子邮件并继续运行foreach循环。

示例:

private $entityManager;

public function __construct(EntityManagerInterface $entityManager)
{
    $this->entityManager = $entityManager;
}

public function testMethod(array $entities)
{
    foreach ($entities as $entity)
    {
        try 
        {
            $entity = new MyEntity();
            $entity->setSomeData();
            $this->entityManager->persist($entity);
            $this->entityManager->flush();
        } catch (\Exception $e)
        {
          //SEND EMAIL
        }
    }
}

有时候,我收到一条消息“ EntityManager is close。”,由PdoException抛出。

重置实体管理器以保持循环的最佳方法是什么?

NB:这是示例代码。我不会发送电子邮件或刷新每个错误。

1 个答案:

答案 0 :(得分:1)

您可以采取一些措施来提高性能:您只需在循环外调用即可。这样,只有在所有内存结尾时才刷新内存。 $this->entityManager->flush();

但是如果您需要在引发异常后继续保存内容,则可以尝试致电$this->getDoctrine()->resetManager();