如何从控制器外部使用Symfony2.2服务


How to use a Symfony2.2 service from ouside of the controller?

我在Symfony应用程序中有一个服务,我从控制器中知道我们可以将其与功能$this->get('MyService');一起使用但从我的控制器外的脚本,我应该如何调用它?

你必须在bundle的服务配置(这里假设是yml配置)中将外部控制器类注册为服务

services:
    your_service_name:
        class:     Your/NonController/Class
        arguments: ['@service_you_want_to_inject']

现在在你想要使用注入服务的类中:

// Your/NonController/Class.php
protected $myService;
// your 'service_you_want_to_inject' will be injected here automatically
public function __construct($my_service)
{
    $this->myService = $my_service;
}

记住,要使依赖注入发生,你必须现在就把这个类当作服务来使用——否则注入不会自动发生。

你现在可以像往常一样在控制器中获得你新创建的服务了:

// 'service_you_want_to_inject' will be automatically injected in the constructor
$this->get('your_service_name');      

也有setter注入和属性注入,但这超出了这个问题的范围…要了解更多关于DI的信息,请参阅symfony文档中的"服务容器"一章。