Symfony 2依赖注入:是否可以通过类名获得服务


Symfony 2 Dependency Injection: is it possible to get a service by class name?

传统上,您会以这种方式使用服务容器:

$container->get('my_service');

然而,假设一个特定类只存在一个定义,我想通过类名获得这个服务:

$container->xxx('My'Application'Service');

服务容器可以这样做吗?

这是可能的,因为Symfony 3.3:

例如,如果您有这样的UserManager:

services:
# ...
# traditional service definition
app.manager.user:
    class: AppBundle'EventListener'UserManager
    tags:  ['kernel.event_subscriber']

然后你可以通过以下方式获得它:

// before Symfony 3.3
$this->get('app.manager.user')->save($user);
// Symfony 3.3+
$this->get(UserManager::class)->save($user);

不,这是不可能的,因为:

  • 一个类可以(在很多情况下)出现不止一次[1]
  • 使用DIC的主要原因是将具体实现解耦从它的使用情况来看,因此如果你想的话,你根本不需要DIC具体类的实例

[1] 说这一个类只出现一次,并不是在DIC本身中实现边缘用例的好论据。