BenMorel
BenMorel

Reputation: 36514

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

Traditionally, you would use the service container this way:

$container->get('my_service');

However, provided that only one definition of a specific class exists, I'd like to get this service by class name:

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

Is this possible with the service container?

Upvotes: 3

Views: 2894

Answers (2)

karpatil
karpatil

Reputation: 68

It is possible since Symfony 3.3:

For example if you have a UserManager like this:

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

then you can get it in the following ways:

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

// Symfony 3.3+
$this->get(UserManager::class)->save($user);

source

Upvotes: 4

KingCrunch
KingCrunch

Reputation: 131891

No, it's not possible, because:

  • a class can (and in many cases will) appear more than once [1]
  • the main reason to use a DIC is to decouple a concrete implementation from its usage and therefore you don't need a DIC at all, if you want an instance of a concrete class.

[1] Saying, that this one class appears only once is no good argument to implement an edge case into the DIC itself.

Upvotes: 4

Related Questions