|
| 1 | +.. index:: |
| 2 | + single: Dependency Injection; Lazy Services |
| 3 | + |
| 4 | +Lazy Services |
| 5 | +============= |
| 6 | + |
| 7 | +.. versionadded:: 2.3 |
| 8 | + Lazy services were added in Symfony 2.3. |
| 9 | + |
| 10 | +Configuring lazy services |
| 11 | +------------------------- |
| 12 | + |
| 13 | +In some particular cases where a very heavy service is always requested, |
| 14 | +but not always used, you may want to mark it as ``lazy`` to delay its instantiation. |
| 15 | + |
| 16 | +In order to have services to lazily instantiate, you will first need to install |
| 17 | +the `ProxyManager bridge`_:: |
| 18 | + |
| 19 | + php composer.phar require symfony/proxy-manager-bridge:2.3.* |
| 20 | + |
| 21 | +You can mark the service as ``lazy`` by manipulating its definitions: |
| 22 | + |
| 23 | + |
| 24 | +.. configuration-block:: |
| 25 | + |
| 26 | + .. code-block:: yaml |
| 27 | +
|
| 28 | + services: |
| 29 | + foo: |
| 30 | + class: Example\Foo |
| 31 | + lazy: true |
| 32 | +
|
| 33 | + .. code-block:: xml |
| 34 | +
|
| 35 | + <service id="foo" class="Example\Foo" lazy="true" /> |
| 36 | +
|
| 37 | + .. code-block:: php |
| 38 | +
|
| 39 | + $definition = new Definition('Example\Foo'); |
| 40 | + $definition->setLazy(true); |
| 41 | + $container->setDefinition('foo', $definition); |
| 42 | +
|
| 43 | +You can then require the service from the container:: |
| 44 | + |
| 45 | + $service = $container->get($serviceId); |
| 46 | + |
| 47 | +At this point the retrieved ``$service`` should be a virtual `proxy`_ with the same |
| 48 | +signature of the class representing the service. |
| 49 | + |
| 50 | +.. note:: |
| 51 | + |
| 52 | + If you don't install the `ProxyManager bridge`_, the container will just skip |
| 53 | + over the ``lazy`` flag and simply instantiate the service as it would normally do. |
| 54 | + |
| 55 | +The proxy gets initialized and the actual service is instantiated as soon as you interact |
| 56 | +in any way with this object. |
| 57 | + |
| 58 | +Additional resources |
| 59 | +-------------------- |
| 60 | + |
| 61 | + |
| 62 | +You can read more about how proxies are instantiated, generated and initialized in |
| 63 | +the `documentation of ProxyManager`_. |
| 64 | + |
| 65 | + |
| 66 | +.. _`ProxyManager bridge`: https://github.com/symfony/symfony/tree/2.3/src/Symfony/Bridge/ProxyManager |
| 67 | +.. _`proxy`: http://en.wikipedia.org/wiki/Proxy_pattern |
| 68 | +.. _`documentation of ProxyManager`: https://github.com/Ocramius/ProxyManager/blob/master/docs/lazy-loading-value-holder.md |
0 commit comments