Tag: orm

  • Doctrine 2 Exception EntityManager is closed

    Doctrine 2 Exception EntityManager is closed

    Doctrine 2’s EntityManager class will permanently close connections upon failed transactions. Thus, further requests using these closed instances will fail with the following exception:

    Doctrine\\ORM\\ORMException' with message 'The EntityManager is closed.
    

    So, make sure to check your EntityManager’s state before your actual tasks:

    if (!$entityManager->isOpen()) {
      $entityManager = $entityManager->create(
        $entityManager->getConnection(), $entityManager->getConfiguration());
    }
    

    Better, create a function called getEntityManager that takes care of this check and makes sure that you always get a viable instance of EntityManager to work with:

    private static function getEntityManager() {
      if (!self::$entityManager->isOpen()) {
        self::$entityManager = self::$entityManager->create(
          self::$entityManager->getConnection(), self::$entityManager->getConfiguration());
      }
    
      return self::$entityManager;
    }
    

    So you can use:

    self::$entityManager = self::getEntityManager();
    self::$entityManager->persist($some_entity_instance);
    self::$entityManager->flush();
    

    Thats’s it.