【问题标题】:When to use Entity Manager in Symfony2何时在 Symfony2 中使用实体管理器
【发布时间】:2012-08-04 12:17:50
【问题描述】:

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

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

$em = $this->getDoctrine()->getEntityManager();
$products = $em->getRepository('AcmeStoreBundle:Product')
        ->findAllOrderedByName();

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

$product = $this->getDoctrine()
        ->getRepository('AcmeStoreBundle:Product')
        ->find($id);

所以我实际上在没有获取实体管理器的情况下尝试了第一个示例:

$repository = $this->getDoctrine()
        ->getRepository('AcmeStoreBundle:Product');
$products = $repository->findAllOrderedByName();

得到了同样的结果。

那么我什么时候真正需要实体管理器,什么时候可以一次访问存储库?

【问题讨论】:

    标签: symfony doctrine-orm entitymanager


    【解决方案1】:

    如果您计划使用实体管理器执行多项操作(例如获取存储库、持久化实体、刷新等),请先获取实体管理器并将其存储在变量中。否则,您可以从实体管理器获取存储库,并在一行中调用存储库类上所需的任何方法。两种方式都会奏效。这只是编码风格和您的需求的问题。

    【讨论】:

      【解决方案2】:

      查看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();
      

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

      $repository = $this->getDoctrine()->getRepository('AcmeStoreBundle:Product');
      $product    = $repository->find(1);
      

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

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

      【讨论】:

      • 我已经知道在使用flush()时需要使用实体管理器。此外,使用getProductRepository() 函数的想法可能很有用,谢谢!
      • @MatsRietdijk 很高兴为您提供帮助!我总是将$this->get('some service') 包装在我的BaseController 中的自定义函数中以获得自动完成...
      • AcmeStoreBundle:Product 的位置在哪里可以在我的 Symfony 应用程序中找到Product
      • YouApplication\src\Bundle\ToolsBundle\Repository\ProductRepository.php
      【解决方案3】:

      我认为getDoctrine()->getRepository() 只是getDoctrine()->getEntityManager()->getRepository() 的快捷方式。没有检查源代码,但对我来说听起来很合理。

      【讨论】:

      • 谢谢,好像是捷径。
      猜你喜欢
      • 2014-04-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 2015-09-02
      • 2014-11-25
      相关资源
      最近更新 更多