当我扩展ContainerAware或实现ContainerAwareInterface时,该服务不会调用setContainer.
class CustomService implements ContainerAwareInterface
{
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}
Run Code Online (Sandbox Code Playgroud)
如何在没有注射的情况下使用我服务的容器?是否需要将容器对象传递给构造函数或setter?
在services.yml文件中定义
services:
bundle.service_name:
class: ...
calls:
- [ setContainer, [ @service_container ] ]
Run Code Online (Sandbox Code Playgroud)
仅实现ContainerAwareorContainerAwareInterface是不够的。您必须使用service_containeras 参数调用 setter 注入。但不建议注入整个容器。最好只注入您真正需要的服务。
您必须将服务名称放在引号中:
services:
bundle.service_name:
class: ...
calls:
- [ setContainer, [ '@service_container' ]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10636 次 |
| 最近记录: |