symfonydoctrine-orm

beginTransaction in symfomy2


I'm learning and I have more doubts about Doctrine and Symfony

What is the best practice for persist? Now i'm using this:

try {
        $em = $this->getEm();
        $em->beginTransaction();
        $product = new \Acme\StoreBundle\Entity\Product();
        $product->setName('foo');
        $product->setPrice('19.99');
        $em->persist($product);
        $em->flush();
        $em->commit();
    } catch (\Exception $e) {
        $em->rollback();
        throw $e;
    }

But In symfony documentation, there isn't beginTransaction. And What is the different between $em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()? When to use one or the other


Solution

  • For what you're doing there, you wouldn't need to use beginTransaction() and commit() since flush() would basically take care of that.

    persist() is used for inserting new entities into your database, and flush() actually performs the database operation. If you already have the entity fetched and then modify it, you don't need persist() since Doctrine is already managing it.

    You would use $em = $this->getDoctrine()->getManager(); when you are in a Symfony controller to get the entity manager.

    When you call $this->getDoctrine() it returns the Doctrine Registry service (equivalent to $this->container->get('doctrine');) which references all of your Doctrine connections and entity managers.

    Further documentation:

    http://doctrine-orm.readthedocs.org/en/latest/reference/transactions-and-concurrency.html http://symfony.com/doc/current/book/doctrine.html

    The best way to learn is to read the docs and experiment. Symfony documentation provides excellent examples and explanations.