New in version 2.3: Lazy services were introduced in Symfony 2.3.
Why Lazy Services?¶
In some cases, you may want to inject a service that is a bit heavy to instantiate,
but is not always used inside your object. For example, imagine you have
NewsletterManager and you inject a
mailer service into it. Only
a few methods on your
NewsletterManager actually use the
but even when you don't need it, a
mailer service is always instantiated
in order to construct your
Configuring lazy services is one answer to this. With a lazy service, a
"proxy" of the
mailer service is actually injected. It looks and acts
just like the
mailer, except that the
mailer isn't actually instantiated
until you interact with the proxy in some way.
In order to use the lazy service instantiation, you will first need to install
$ composer require ocramius/proxy-manager
If you're not using the full-stack framework, you also have to install the ProxyManager bridge
$ composer require symfony/proxy-manager-bridge:~2.3
You can mark the service as
lazy by manipulating its definition:
1 2 3 4 5
# app/config/services.yml services: app.twig_extension: class: AppBundle\Twig\AppExtension lazy: true
1 2 3 4 5 6 7 8 9 10 11
<!-- app/config/services.xml --> <?xml version="1.0" encoding="UTF-8" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <services> <service id="app.twig_extension" class="AppBundle\Twig\AppExtension" lazy="true" /> </services> </container>
1 2 3 4 5
// app/config/services.php use AppBundle\Twig\AppExtension; $container->register('app.twig_extension', AppExtension::class) ->setLazy(true);
Once you inject the service into another service, a virtual proxy with the
same signature of the class representing the service should be injected. The
same happens when calling
The actual class will be instantiated as soon as you try to interact with the service (e.g. call one of its methods).
To check if your proxy works you can simply check the interface of the received object:
dump(class_implements($service)); // the output should include "ProxyManager\Proxy\LazyLoadingInterface"
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.