何时在Symfony2中使用实体管理器

Mat*_*ijk 15 entitymanager symfony doctrine-orm

目前我正在学习如何使用Symfony2.我到了解他们如何使用Doctrine的地步.

在给出的示例中,他们有时使用实体管理器:

$em = $this->getDoctrine()->getEntityManager();
$products = $em->getRepository('AcmeStoreBundle:Product')
        ->findAllOrderedByName();
Run Code Online (Sandbox Code Playgroud)

在其他示例中,不使用实体管理器:

$product = $this->getDoctrine()
        ->getRepository('AcmeStoreBundle:Product')
        ->find($id);
Run Code Online (Sandbox Code Playgroud)

所以我实际上尝试了第一个例子而没有获得实体管理器:

$repository = $this->getDoctrine()
        ->getRepository('AcmeStoreBundle:Product');
$products = $repository->findAllOrderedByName();
Run Code Online (Sandbox Code Playgroud)

并得到了相同的结果.

那么我什么时候才真正需要实体管理器?什么时候可以立即去存储库呢?

gre*_*emo 29

看着等于,一个实例.Registry提供:Controller getDoctrine()$this->get('doctrine')Symfony\Bundle\DoctrineBundle\Registry

因此,$this->getDoctrine()->getRepository()等于$this->getDoctrine()->getEntityManager()->getRepository().

当您想要持久化或删除实体时,实体管理器非常有用:

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

$em->persist($myEntity);
$em->flush();
Run Code Online (Sandbox Code Playgroud)

如果您只是获取数据,则只能获取存储库:

$repository = $this->getDoctrine()->getRepository('AcmeStoreBundle:Product');
$product    = $repository->find(1);
Run Code Online (Sandbox Code Playgroud)

或者更好的是,如果您使用自定义存储库,请包装getRepository()控制器函数,因为您可以从IDE获得自动完成功能:

/**
 * @return \Acme\HelloBundle\Repository\ProductRepository
 */
protected function getProductRepository()
{
    return $this->getDoctrine()->getRepository('AcmeHelloBundle:Product');
}
Run Code Online (Sandbox Code Playgroud)