symfony - 访问事件订阅者内部的服务

标签 symfony dependency-injection lifecycle

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

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);

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

最佳答案

Cerad 已经回答了,我将详细说明:

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

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 代码中,将注入(inject)的服务分配给一个类变量,以便以后能够访问它:
...
class SearchIndexerSubscriber implements EventSubscriber {

private $myservice;

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

从订阅者中的任何方法通过类变量访问服务方法:
$this->myservice->refreshMyField($document);

Listeners/subscribers in Symfony2

Services in Symfony2

新年快乐。

关于symfony - 访问事件订阅者内部的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27727629/

相关文章:

spring-security - Spring Security 配置循环依赖错误

android - 媒体播放器在广播 Intent 停止后不会停止播放音频文件

javascript - Angular 2 - 延迟加载模块的生命周期 Hook

javascript - 为什么在 componentDidUpdate 中比较数组不会导致无限循环?

php - Symfony – “Object of class DateTime could not be converted to string” 持久化实体

php - 如何将 Angular 与 Symfony 集成

php - 如何保留依赖注入(inject)容器 (PHP) 的实例

c# - 类库中的 IoC。在哪里引导

Symfony 4 - 自定义文件夹结构和服务

apache - Symfony Heroku 部署 : Assets Not Accessible