|
| 1 | +.. index:: |
| 2 | + single: DependencyInjection; Synthetic Services |
| 3 | + |
| 4 | +How to Inject Instances into the Container |
| 5 | +------------------------------------------ |
| 6 | + |
| 7 | +When using the container in your application, you sometimes need to inject |
| 8 | +an instance instead of configuring the container to create a new instance. |
| 9 | + |
| 10 | +For instance, the ``kernel`` service in Symfony is injected into the container |
| 11 | +from within the ``Kernel`` class:: |
| 12 | + |
| 13 | + // ... |
| 14 | + abstract class Kernel implements KernelInterface, TerminableInterface |
| 15 | + { |
| 16 | + // ... |
| 17 | + |
| 18 | + protected function initializeContainer() |
| 19 | + { |
| 20 | + // ... |
| 21 | + $this->container->set('kernel', $this); |
| 22 | + |
| 23 | + // ... |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | +Services that are set at runtime are called *synthetic services*. This service |
| 28 | +has to be configured in the container, so the container knows the service does |
| 29 | +exist during compilation (otherwise, services depending on this ``kernel`` |
| 30 | +service will get a "service does not exist" error). |
| 31 | + |
| 32 | +In order to do so, mark the service as synthetic in your service definition |
| 33 | +configuration: |
| 34 | + |
| 35 | +.. configuration-block:: |
| 36 | + |
| 37 | + .. code-block:: yaml |
| 38 | +
|
| 39 | + services: |
| 40 | +
|
| 41 | + // synthetic services don't specify a class |
| 42 | + app.synthetic_service: |
| 43 | + synthetic: true |
| 44 | +
|
| 45 | + .. code-block:: xml |
| 46 | +
|
| 47 | + <?xml version="1.0" encoding="UTF-8" ?> |
| 48 | + <container xmlns="http://symfony.com/schema/dic/services" |
| 49 | + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 50 | + xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> |
| 51 | +
|
| 52 | + <services> |
| 53 | +
|
| 54 | + <!-- synthetic services don't specify a class --> |
| 55 | + <service id="app.synthetic_service" synthetic="true" /> |
| 56 | +
|
| 57 | + </services> |
| 58 | + </container> |
| 59 | +
|
| 60 | + .. code-block:: php |
| 61 | +
|
| 62 | + // synthetic services don't specify a class |
| 63 | + $container->register('app.synthetic_service') |
| 64 | + ->setSynthetic(true) |
| 65 | + ; |
| 66 | +
|
| 67 | +Now, you can inject the instance in the container using |
| 68 | +:method:`Container::set() <Symfony\\Component\\DependencyInjection\\Container::set>`:: |
| 69 | + |
| 70 | + // instantiate the synthetic service |
| 71 | + $theService = ...; |
| 72 | + $container->set('app.synthetic_service', $theService); |
0 commit comments