Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Service Container
  4. Lazy Services
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

  • Why Lazy Services?
  • Configuration
  • Interface Proxifying

Lazy Services

Edit this page

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, but you can use Interface Proxifying to work around this limitation.

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

6.2

Starting from Symfony 6.2, service laziness is supported out of the box without having to install any additional package.

Configuration

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

  • YAML
  • XML
  • PHP
1
2
3
4
# config/services.yaml
services:
    App\Twig\AppExtension:
        lazy: true
1
2
3
4
5
6
7
8
9
10
11
<!-- 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
        https://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="App\Twig\AppExtension" lazy="true"/>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use App\Twig\AppExtension;

return function(ContainerConfigurator $containerConfigurator) {
    $services = $containerConfigurator->services();

    $services->set(AppExtension::class)->lazy();
};

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:

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

You can also configure your service's laziness thanks to the Autoconfigure attribute. For example, to define your service as lazy use the following:

1
2
3
4
5
6
7
8
9
10
namespace App\Twig;

use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
use Twig\Extension\ExtensionInterface;

#[Autoconfigure(lazy: true)]
class AppExtension implements ExtensionInterface
{
    // ...
}

5.4

The Autoconfigure attribute was introduced in Symfony 5.4.

Interface Proxifying

Under the hood, proxies generated to lazily load services inherit from the class used by the service. However, sometimes this is not possible at all (e.g. because the class is final and can not be extended) or not convenient.

To workaround this limitation, you can configure a proxy to only implement specific interfaces.

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
# config/services.yaml
services:
    App\Twig\AppExtension:
        lazy: 'Twig\Extension\ExtensionInterface'
        # or a complete definition:
        lazy: true
        tags:
            - { name: 'proxy', interface: 'Twig\Extension\ExtensionInterface' }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- 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
        https://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="App\Twig\AppExtension" lazy="Twig\Extension\ExtensionInterface"/>
        <!-- or a complete definition: -->
        <service id="App\Twig\AppExtension" lazy="true">
            <tag name="proxy" interface="Twig\Extension\ExtensionInterface"/>
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use App\Twig\AppExtension;
use Twig\Extension\ExtensionInterface;

return function(ContainerConfigurator $containerConfigurator) {
    $services = $containerConfigurator->services();

    $services->set(AppExtension::class)
        ->lazy()
        ->tag('proxy', ['interface' => ExtensionInterface::class])
    ;
};

Just like in the Configuration section, you can use the Autoconfigure attribute to configure the interface to proxify by passing its FQCN as the lazy parameter value:

1
2
3
4
5
6
7
8
9
10
namespace App\Twig;

use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
use Twig\Extension\ExtensionInterface;

#[Autoconfigure(lazy: ExtensionInterface::class)]
class AppExtension implements ExtensionInterface
{
    // ...
}

5.4

The Autoconfigure attribute was introduced in Symfony 5.4.

The virtual proxy injected into other services will only implement the specified interfaces and will not extend the original service class, allowing to lazy load services using final classes. You can configure the proxy to implement multiple interfaces by adding new "proxy" tags.

Tip

This feature can also act as a safe guard: given that the proxy does not extend the original class, only the methods defined by the interface can be called, preventing to call implementation specific methods. It also prevents injecting the dependency at all if you type-hinted a concrete implementation instead of the interface.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:

Symfony 6.2 is backed by

Symfony 6.2 is backed by

Become certified from home

Become certified from home

Check Code Performance in Dev, Test, Staging & Production

Check Code Performance in Dev, Test, Staging & Production

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of tarlepp, a Symfony contributor

Thanks tarlepp for being a Symfony contributor

2 commits • 158 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia