【问题标题】:How to reopen Doctrine Entity Manager after DBALExceptionDBALException 后如何重新打开 Doctrine Entity Manager
【发布时间】:2015-01-25 00:09:10
【问题描述】:

我有一个带有 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;
}

如何解决?

【问题讨论】:

标签: php symfony doctrine-orm doctrine


【解决方案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);

【讨论】:

  • 您能解释一下这个中间件的用途和工作原理吗?
【解决方案2】:

您可以像这样手动重置实体管理器:

//...
} 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;
} 
//...

【讨论】:

  • 即使在重置实体管理器后也可能出现问题 - github.com/symfony/symfony/issues/5339
  • 它对我不起作用.. 这是 Symfony 或 Doctrine 的错误?
  • 其中一些方法在较新的版本中不可用。
猜你喜欢
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 2015-03-20
  • 2014-09-30
  • 2019-05-20
相关资源
最近更新 更多