bet*_*eth 9 lifecycle dependency-injection symfony
我有一个带有Doctrine事件的事件订阅者.在其中,我试图调用我已注册的服务.我已经在控制器中调用它并且它在那里工作,但是当我尝试在我的事件订阅者中调用它时,我收到一个错误:
Attempted to call method "get" on class "Path\To\My\Class".
Did you mean to call "getSubscribedEvents"?
Run Code Online (Sandbox Code Playgroud)
代码如下所示:
$embedcode_service = $this->get('myproject.mynamespace.myfield.update');
$embedcode_service->refreshMyField($document);
Run Code Online (Sandbox Code Playgroud)
为什么我无法在此活动订阅者中访问我的服务?我怎样才能访问它?
塞拉德已经回答我要详细说明:
在您的订阅者中注入您的服务:
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 }
...
Run Code Online (Sandbox Code Playgroud)
在您的订阅者的PHP代码中,将注入的服务分配给类变量,以便以后能够访问它:
...
class SearchIndexerSubscriber implements EventSubscriber {
private $myservice;
public function __construct($myservice) {
$this->myservice = $myservice;
}
...
Run Code Online (Sandbox Code Playgroud)
通过订阅者中任何方法的类变量访问服务方法:
$this->myservice->refreshMyField($document);
Run Code Online (Sandbox Code Playgroud)
新年快乐.
| 归档时间: |
|
| 查看次数: |
6280 次 |
| 最近记录: |