访问事件订阅者中的服务

时间:2015-01-01 01:05:57

标签: symfony dependency-injection lifecycle

我有一个带有Doctrine事件的事件订阅者。在其中,我试图调用我已注册的服务。我已经在控制器中调用它并且它在那里工作,但当我尝试在我的事件订阅者中调用它时,我收到错误:

Attempted to call method "get" on class "Path\To\My\Class".
Did you mean to call "getSubscribedEvents"?

代码如下所示:

$embedcode_service = $this->get('myproject.mynamespace.myfield.update');
$embedcode_service->refreshMyField($document);

为什么我无法在此活动订阅者中访问我的服务?我怎样才能访问它?

1 个答案:

答案 0 :(得分:8)

Cerad已经回答我要详细说明:

在订阅者中注入您的服务:

services:
    ...
    my.subscriber:
            class: Acme\SearchBundle\EventListener\SearchIndexerSubscriber
            # Service you want to inject
            arguments: [ @service_i_want_to_inject.custom ]
            tags:
                - { name: doctrine.event_subscriber, connection: default }
   ...

在订阅者的php代码中,将注入的服务分配给类变量,以便以后能够访问它:

...
class SearchIndexerSubscriber implements EventSubscriber {

private $myservice;

public function __construct($myservice) {
    $this->myservice = $myservice;
}
...

通过订阅者中任何方法的类变量访问服务方法:

$this->myservice->refreshMyField($document);

Listeners/subscribers in Symfony2

Services in Symfony2

新年快乐。