在Symfony2项目中,当您使用控制器(Controller)时,可以通过在
this
上调用getDoctrine()
来访问Doctrine,例如:$this->getDoctrine();
通过这种方式,我可以访问Doctrine Entity的存储库。
假设在Symfony2项目中有一个通用的PHP类。如何检索Doctrine? 我想必定有这样的服务来获取它,但我不知道是哪一个。
$this->getDoctrine()->getRepository('AcmeUserBundle:Address');
,我也可以按以下方式获取EntityManager:$this->getDoctrine()->getEntityManager()
。然而,已知EntityManager,我如何获取存储库?如果可以的话,那么答案就是你的! - JeanValjeanController
中的getDoctrine
,它只是调用$this->container->get('doctrine')
。所以你可以在你自己的服务中注入doctrine
,并做同样的事情。但是,您也可以通过调用$entityManager->getRepository('...')
来实现相同的效果。 - Ondrej Slinták