Permalink
Browse files

[DoctrineBundle] split Registry::getEntityManager() in two methods

Resetting an entity manager has a lot of consequences and the developer should
be aware of that. So, instead of implicitly reset an entity manager when it is
closed, the developer should reset it by hand if he thinks that this is
possible:

    $em = $this->get('registry')->getEntityManager();
    $em->getConnection()->beginTransaction(); // suspend auto-commit
    try {
        //... do some work
    } catch (Exception $e) {
        $em->getConnection()->rollback();
        $em->close();

        $this->get('registry')->resetEntityManager();
    }

    // you will get a new one
    $em = $this->get('registry')->getEntityManager();
  • Loading branch information...
fabpot committed May 4, 2011
1 parent dd692c0 commit 86d0ddb4e3e957671df26e0ad98249ee566f150c
Showing with 31 additions and 8 deletions.
  1. +31 −8 src/Symfony/Bundle/DoctrineBundle/Registry.php
@@ -87,7 +87,7 @@ public function getDefaultEntityManagerName()
}
/**
- * Gets the named entity manager.
+ * Gets a named entity manager.
*
* @param string $name The entity manager name (null for the default one)
*
@@ -103,16 +103,39 @@ public function getEntityManager($name = null)
throw new \InvalidArgumentException(sprintf('Doctrine EntityManager named "%s" does not exist.', $name));
}
- $em = $this->container->get($this->entityManagers[$name]);
+ return $this->container->get($this->entityManagers[$name]);
+ }
+
+ /**
+ * Resets a named entity manager.
+ *
+ * This method is useful when an entity manager has been closed
+ * because of a rollbacked transaction AND when you think that
+ * it makes sense to get a new one to replace the closed one.
+ *
+ * Be warned that you will get a brand new entity manager as
+ * the existing one is not useable anymore. This means that any
+ * other object with a dependency on this entity manager will
+ * hold an obsolete reference. You can inject the registry instead
+ * to avoid this problem.
+ *
+ * @param string $name The entity manager name (null for the default one)
+ *
+ * @return EntityManager
+ */
+ public function resetEntityManager($name = null)
+ {
+ if (null === $name) {
+ $name = $this->defaultEntityManager;
+ }
- if (!$em->isOpen()) {
- // force the creation of a new entity manager
- // if the current one is closed
- $this->container->set($this->entityManagers[$name], null);
- $em = $this->container->get($this->entityManagers[$name]);
+ if (!isset($this->entityManagers[$name])) {
+ throw new \InvalidArgumentException(sprintf('Doctrine EntityManager named "%s" does not exist.', $name));
}
- return $em;
+ // force the creation of a new entity manager
+ // if the current one is closed
+ $this->container->set($this->entityManagers[$name], null);
}
/**

0 comments on commit 86d0ddb

Please sign in to comment.