SymfonyWorld Online 2021 Winter Edition December 9 – 10, 2021 100% Online 25 talks and 10 workshops

New in Symfony 5.1: Simpler service decoration

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Nicolas Grekas
in #36389.

Service decoration is used in Symfony applications to change the behavior of some service without replacing it entirely. To do that, you need to inject the original service as an argument of the new decorating service. The problem is that the original service no longer exists, so you can't use its original ID.

In previous Symfony versions you needed to use the syntax decorating service ID + .inner to refer to that service. This quickly becomes cumbersome in YAML/XML when using PHP classes as service IDs. That's why in Symfony 5.1 we've simplified this feature to always use .inner to refer to the original service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# config/services.yaml
services:
    App\Mailer: ~

    # Before
    App\SpecialMailer:
        decorates: App\Mailer
        arguments: ['@App\SpecialMailer.inner']

    # After
    App\SpecialMailer:
        decorates: App\Mailer
        arguments: ['@.inner']
Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

Great!
If you are using autowiring (the default since Symfony 4), you can also omit the “arguments” key: Symfony will be smart enough to wire the decorator automatically.
thank you Kévin for your remark!
Great!

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.