[英]How can I access the symfony Service Container in my Service?
I have created a new Service, and its job involves calling functions on other services that must be loaded by name at runtime. 我创建了一个新的Service,它的工作涉及调用必须在运行时按名称加载的其他服务上的函数。 So, I can't pass in a static set of services to my service, I want it to actually be able to call
get()
on the service container itself. 所以,我无法将一组静态服务传递给我的服务,我希望它实际上能够在服务容器本身上调用
get()
。 The Symfony docs haven't been helpful for describing how to do this outside of a Controller class where I can just call $this->get(). Symfony文档没有帮助描述如何在Controller类之外执行此操作,我可以在其中调用$ this-> get()。 Anyone know how?
谁知道怎么样?
You have two possible solutions : 您有两种可能的解决方案:
1. Inject the service container : 1.注入服务容器:
<argument type="service" id="service_container" />
And then in your class : 然后在你的班上:
use Symfony\Component\DependencyInjection\Container;
//...
public function __construct(Container $container, ...) {
2. Extend ContainerAware class 2.扩展ContainerAware类
use Symfony\Component\DependencyInjection\ContainerAware;
class YourService extends ContainerAware
{
public function someMethod($serviceName)
{
$this->container->get($serviceName)->doSomething();
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.