简体   繁体   English

Symfony实体管理员电话

[英]Symfony Entity Manager Call

I want to know if there's any difference to call Entity manager on a Symfony3 Controller: 我想知道在Symfony3控制器上调用实体管理器是否有任何区别:

$this->getDoctrine()->getManager()

And: 和:

$this->get('doctrine.orm.entity_manager');

Performance? 性能? More Correct? 更正确吗?

Thanks so much in advance, Carl Dev 在此先感谢Carl Dev

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? 我认为不,Symfony有一个漂亮的功能称为“依赖注入”( https://symfony.com/doc/current/components/dependency_injection.html ),您从来没有直接调用过服务,为什么? 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. 如果要测试该方法的调用,则必须将Manager指向某个位置,因此测试取决于基础结构。

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. 您可以模拟该实体管理器或实现一个onMemoryEntityManager来删除该依赖项。

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 https://zh.wikipedia.org/wiki/Dependency_injectionhttps://symfony.com/doc/3.3/components/dependency_injection.html

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. 例如,当您需要将实体管理器作为类中的服务时,第二种方法很有用,并且是获取理论实体管理器的正确方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM