1

TL;DR: I have noted that some tutorials are using an extra method call to retrieve a variable, in my case EntityManager of Doctrine. Is it generally a good idea to use such extra method call, when it seemingly adds overhead, even if this overhead is "just a little bit" of overhead? In my case I am talking about the code that uses $this->getEntityManager() and does not use $this->entityManager directly

Instantiation of EntityManager in Doctrine is an expensive procedure. There are some (rare) times where I do not need an EntityManager to do something although most of the times I do.

I have noticed that many tutorials use an "extra" method to retrieve EntityManager, like so (see getEntityManager):

class GenericRepository
{

    /**
     *
     * @var EntityManager
     */
    protected $em;

    /**
     *
     * @return EntityManager
     */
    final public function getEntityManager()
    {
        if ($this->em === null)
            $this->em = DoctrineConnector::getEntityManager();

        return $this->em;
    }
}

and later in my code I have something like this:

class CustomRepository extends GenericRepository
{

    /**
     * Looks up Category Entity by its string name
     *
     * @param string $name
     * @return Product
     */
    function getProduct($partNumber)
    {
        $product = $this->getEntityManager() //<--calling entity Manager indirectly
        ->getRepository(ProductEntity::class)
        ->findOneBy(array(
            'model' => $partNumber
        ));

        return $product;
    }
}

Question

I can replace getEntityManager() call above with em, if in my GenericRepository class I initialize the repository right away at construction time. I can then shorten my code to be like below and avoid an extra getEntityManager() method call, like so:

        $product = $this->em  //<-- this is different, using em directly
        ->getRepository(ProductEntity::class)
        ->findOneBy(array(
            'model' => $partNumber
        ));

em will be guaranteed to be non-null in that case if I initialize it at construction time.

Why not instead refer to the $em directly and remove lazy initialization?

What would be some reasons to keep getEntityManager() in my code and to keep using lazy initialization at the expense of the overhead of an extra method call?

Dennis
  • 8,157
  • 5
  • 36
  • 68

1 Answers1

1

If you use lazy instantiation, and a previous transaction resulted an exception and rollback, then the reference you're keeping to the EntityManager will point to an EntityManager in the closed state. Any query will fail. The reason to get the EM from Doctrine every time is that it will give you a new instance of an EM if the previous EM was closed due to a rollback.

At least, that's the behavior from Symfony2+ IIRC. I don't believe that's specific to symfony but it might be.

RibaldEddie
  • 3,168
  • 1
  • 15
  • 17