Reputation:
I want to know if there's any difference to call Entity manager on a Symfony3 Controller:
$this->getDoctrine()->getManager()
And:
$this->get('doctrine.orm.entity_manager');
Performance? More Correct?
Thanks so much in advance, Carl Dev
Upvotes: 0
Views: 765
Reputation: 264
I think both are the same a performance level, but are those correct? i think no, Symfony have a beautiful feature call "dependency injection" (https://symfony.com/doc/current/components/dependency_injection.html), you have never ever to call a service directly, why? because is hard to test, for example:
public function test()
{
$manager = $this->getDoctrine()->getManager();
$manager->persist(new MyClass());
$manager->flush();
}
If you want to test this call that method, you have to have a Manager point to somewhere, so your test depends on infrastructure.
Now, imagine this:
public function test(EntityManager $manager)
{
$manager->persist(new MyClass());
$manager->flush();
}
You can mock that entity manager or implement a onMemoryEntityManager removing that dependency.
There are so many theory behind this i suggest to read this:
https://en.wikipedia.org/wiki/Dependency_injection and https://symfony.com/doc/3.3/components/dependency_injection.html
Upvotes: 1
Reputation: 35973
The first method is only available when you extending the base controller so it's possibile to use into a controller usually. It's the shortcut of the second method.
The second method is useful when you need the entity manager as a service inside your class for example and is the correct way of getting the doctrine entity manager.
Upvotes: 0