在 EntityRepository 中注入 EventDispatcher 的最佳方法是什么?


What is the best way to inject EventDispatcher in EntityRepository?

我想知道在EntityRepository类中注入EventDispatcher的最佳实践是什么。

首先,使用 global 是一种非常糟糕的做法。我强烈建议你不要这样做。
其次,将服务注入存储库似乎不是一个好主意。它经常会违反像单一责任原则这样的法律。

我会创建一个管理器来包装存储库的方法,并触发您需要的事件。有关详细信息,请参阅如何将存储库注入服务。

服务.yml

services:
    my_manager:
        class: Acme'FooBundle'MyManager
        arguments:
            - @acme_foo.repository
            - @event_dispatcher
    acme_foo.repository:
        class: Acme'FooBundle'Repository'FooRepository
        factory_service: doctrine.orm.entity_manager
        factory_method: getRepository
        arguments:
            - "AcmeFooBundle:Foo"

Acme''FooBundle''MyManager

use Acme'FooBundle'Repository'FooRepository;
use Symfony'Component'EventDispatcher'EventDispatcherInterface;
class MyManager
{
    protected $repository;
    protected $dispatcher;
    public function __construct(FooRepository $repository, EventDispatcherInterface $dispatcher)
    {
        $this->repository = $repository;
        $this->dispatcher = $dispatcher;
    }
    public function findFooEntities(array $options = array())
    {
        $event = new PreFindEvent;
        $event->setOptions($options);
        $this->dispatcher->dispatch('find_foo.pre_find', $event);
        $results = $this->repository->findFooEntities($event->getOptions());
        $event = new PostFindEvent;
        $event->setResults($results);
        $this->dispatcher->dispatch('find_foo.post_find', $event);
        return $event->getResults();
    }
}

然后,您可以在控制器中使用它,就像服务一样。

$this->get('my_manager')->findFooEntities($options);

但是,如果确实需要将事件调度程序注入实体,则可以执行此操作

服务.yml

services:
    acme_foo.repository:
        class: Acme'FooBundle'Repository'FooRepository
        factory_service: doctrine.orm.entity_manager
        factory_method: getRepository
        arguments:
            - "AcmeFooBundle:Foo"
        calls:
            - [ "setEventDispatcher", [ @event_dispatcher ] ]

然后,您只需将setEventDispatcher方法添加到存储库中即可。

Acme''FooBundle''Repository''FooRepository

class FooRepository extends EntityRepository
{
    protected $dispatcher;
    public function setEventDispatcher(EventDispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }
    public function findFooEntities(array $options = array())
    {
        $dispatcher = $this->dispatcher;
        // ...
    }
}

只需确保在控制器中使用服务时调用服务而不是存储库即可。

$this->get('acme_foo.repository')->findFooEntities();

不要

$this->getDoctrine()->getManager()->getRepository('AcmeFooBundle:Foo')->findFooEntities();