Symfony2中的依赖注入最佳实践

时间:2017-09-05 22:03:34

标签: symfony dependency-injection

在Symfony2(本例中为2.8)中,将服务注入其他服务时,最佳做法是什么?

/**
 * Checker constructor.
 * @param EntityManager $em
 * @param EventDispatcherInterface $dispatcher
 */
public function __construct(EntityManager $em, EventDispatcherInterface $dispatcher)
{
    $this->repoUser = $em->getRepository(User::class);
    $this->repoPurchase = $em->getRepository(Purchase::class);
    $this->repoTicket = $em->getRepository(Ticket::class);
    $this->dispatcher = $dispatcher;
}

/**
 * Checker constructor.
 * @param UserRepository $ur
 * @param PurchaseRepository $pr
 * @param TicketRepository $tr
 * @param EventDispatcherInterface $dispatcher
 */
public function __construct(UserRepository $ur, PurchaseRepository $pr, TicketRepository $tr, EventDispatcherInterface $dispatcher)
{
    $this->repoUser = $ur;
    $this->repoPurchase = $pr;
    $this->repoTicket = $tr;
    $this->dispatcher = $dispatcher;
}

或明确使用setter并在services.yml中单独设置参数?

我想知道等式的性能部分是什么。

1 个答案:

答案 0 :(得分:7)

两种情况都有利弊。

  • 性能而言,两个选项都相同,因为只有在请求服务实例时才会获得存储库实例。无需手动操作,也可以由DI自动完成。精神化here

      

    容器是懒惰的:它不会实例化服务,直到(除非)你要求它。

  • 如果您打算通过单元测试来覆盖您的服务 - 那么选项2肯定会更好,因为您不需要模拟$ em-> getRepository()在考试开始时打电话。

  • 个人制定者的好处 - 也与单元测试有关。例如,对于一个测试用例,您只需要一个依赖项,另一个测试用例 - 另一个依赖项。因此,您可以在测试中使用setter来设置模拟,并且您不需要将所有模拟传递给构造函数。