Lazy Services

Version: 3.3
Edit this page

Warning: You are browsing the documentation for Symfony 3.3, which is no longer maintained.

Read the updated version of this page for Symfony 5.3 (the current stable version).

Lazy Services

See also

Another way to inject services lazily is via a service locator.

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 a NewsletterManager and you inject a mailer service into it. Only a few methods on your NewsletterManager actually use the mailer, but even when you don't need it, a mailer service is always instantiated in order to construct your NewsletterManager.

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 the ocramius/proxy-manager package:

$ 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


You can mark the service as lazy by manipulating its definition:

  • YAML
  • XML
  • PHP
     lazy:  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 Container::get() directly.

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:

// the output should include "ProxyManager\Proxy\LazyLoadingInterface"


If you don't install the ProxyManager bridge and the ocramius/proxy-manager, the container will just skip over the lazy flag and simply instantiate the service as it would normally do.

Additional Resources

You can read more about how proxies are instantiated, generated and initialized in the documentation of ProxyManager.

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