WARNING: You are browsing the documentation for Symfony 2.3 which is not maintained anymore. Consider upgrading your projects to Symfony 4.1.

How to Inject Instances into the Container

2.3 version
Unmaintained
2.6

How to Inject Instances into the ContainerΒΆ

When using the container in your application, you sometimes need to inject an instance instead of configuring the container to create a new instance.

For instance, if you're using the HttpKernel component with the DependencyInjection component, then the kernel service is injected into the container from within the Kernel class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// ...
abstract class Kernel implements KernelInterface, TerminableInterface
{
    // ...
    protected function initializeContainer()
    {
        // ...
        $this->container->set('kernel', $this);

        // ...
    }
}

The kernel service is called a synthetic service. This service has to be configured in the container, so the container knows the service does exist during compilation (otherwise, services depending on this kernel service will get a "service does not exist" error).

In order to do so, you have to use Definition::setSynthetic():

1
2
3
4
5
6
7
use Symfony\Component\DependencyInjection\Definition;

// synthetic services don't specify a class
$kernelDefinition = new Definition();
$kernelDefinition->setSynthetic(true);

$container->setDefinition('your_service', $kernelDefinition);

Now, you can inject the instance in the container using Container::set():

$yourService = new YourObject();
$container->set('your_service', $yourService);

$container->get('your_service') will now return the same instance as $yourService.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.