get('doctrine')之间的区别; 和getDoctrine();

cut*_*e.S 3 service entity symfony doctrine-orm

在Symfony中,我找到了三种访问doctrine服务和实体管理器的方法,如下所示:

$em = $this->getDoctrine()->getManager();

$em = $this->get('doctrine')->getEntityManager();

$em = $this->container->get('doctrine.orm.entity_manager');
Run Code Online (Sandbox Code Playgroud)

任何人都可以请他们解释他们的分歧,并解释我们何时应该使用其中的哪一个.

Wou*_*r J 6

第一个仅在扩展基本控制器时可用.$this->get('doctrine')正如您在源代码中看到的那样,这是一个快捷方式:

public function getDoctrine()
{
    if (!$this->container->has('doctrine')) {
        throw new \LogicException('The DoctrineBundle is not registered in your application.');
    }

    return $this->container->get('doctrine');
}
Run Code Online (Sandbox Code Playgroud)

$this->get('doctrine')也仅适用于控制器.get也在基本控制器中定义,是一个快捷方式$this->container->get():

public function get($id)
{
    return $this->container->get($id);
}
Run Code Online (Sandbox Code Playgroud)

$this->container->get('doctrine') 是获得学说注册表的完整书面形式.