How to Inject Instances into the Container
Edit this pageWarning: You are browsing the documentation for Symfony 2.3, which is no longer maintained.
Read the updated version of this page for Symfony 6.3 (the current stable version).
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():
1 2
$yourService = new YourObject();
$container->set('your_service', $yourService);
$container->get('your_service')
will now return the same instance as
$yourService
.