Lazy Services

See also

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

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 like the mailer, except that the mailer isn’t actually instantiated until you interact with the proxy in some way.

Caution

Lazy services do not support final classes.

In PHP versions prior to 8.0 lazy services do not support parameters with default values for built-in PHP classes (e.g. PDO).

New in version 6.2: Starting from Symfony 6.2, you don’t have to install any package (e.g. symfony/proxy-manager-bridge) in order to use the lazy service instantiation.

Configuration

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

Once you inject the service into another service, a lazy ghost object with the same signature of the class representing the service should be injected. A lazy ghost object is an object that is created empty and that is able to initialize itself when being accessed for the first time). The same happens when calling Container::get() directly.

To check if your lazy service works you can check the interface of the received object:

dump(class_implements($service));
// the output should include "Symfony\Component\VarExporter\LazyGhostObjectInterface"