getEntityManager() and getDoctrine() in Symfony2

2019-04-24 00:45发布

Is there any difference between these two statements:

$this->getDoctrine()->getEntityManager()->getRepository();

$this->getDoctrine()->getRepository();

Does the difference relate to any OOP concept I am missing out?

3条回答
Fickle 薄情
2楼-- · 2019-04-24 01:31

In general, no difference, since

$this->getDoctrine()->getRepository();

is just a helper for

$this->getDoctrine()->getEntityManager()->getRepository();

You can have several entity managers, and then there will be a slight difference in getting a repository from one:

$this->getDoctrine()->getRepository($entityName, $enityManagerName);
$this->getDoctrine()->getEntityManager($entityManagerName)->getRepository($entityName);

But again, no difference in the result you'll get.

All other things being equal, I'd go with the shortest one.

查看更多
萌系小妹纸
3楼-- · 2019-04-24 01:41

The result is the same, but if you need the entityManager for more than just getting the repository, it might be handy to store it and then recieve the repository as well as do other operations such as flush:

$_em = $this->getDoctrine()->getEntityManager();
$repository = $_em->getRepository();
//...
$_em->flush();

As said before, if you only need to get the Repository, go with the second statement, which is shorter and as easy to read as the first one.

查看更多
做自己的国王
4楼-- · 2019-04-24 01:44

There is no difference. If you look at the source code of AbstractManagerRegistry.php. You can see this code:

public function getRepository($persistentObjectName, $persistentManagerName = null)
{
    return $this->getManager($persistentManagerName)->getRepository($persistentObjectName);
}

As you can see, when you call getRepository(), it first calls getManager() and then getRepository(). I would suggest using the second one as it gives intellisense in IDEs such as PHPStorm. Hope it helps.

查看更多
登录 后发表回答