Baptiste Clavié
Contributed by Baptiste Clavié in #15491

Symfony project can boast about having one of the best deprecation mechanisms among open source projects: internal framework deprecations are noticed years before they are removed, we comply with a strict backwards compatibility promise, we show you deprecation notices in log files, toolbar, web profiler and tests and we recently published a deprecation detector tool.

But what about your own application deprecations? How can you achieve this professional-grade deprecation handling? In order to simplify your work, the DependencyInjection component has added support for deprecated service definitions.

When a service should no longer be used in your application, just define it as deprecated with the deprecated configuration option (supported for XML and PHP services definitions too):

1
2
3
4
# app/config/services.yml
app.markdown_parser:
    class: AppBundle\Markdown\Parser
    deprecated: ~

Now, every time the app.markdown_parser service is created (directly or through a service alias), a deprecation warning is triggered, advising you to stop or to change your uses of that service.

The deprecated version also accepts as its value a message that will be displayed instead of the default one. Defining a custom message is useful to provide alternatives to the deprecated service:

1
2
3
4
# app/config/services.yml
app.markdown_parser:
    class: AppBundle\Markdown\Parser
    deprecated: 'The "%service_id%" service is deprecated. Use "app.content_parser" instead'

Deprecating a service won't trigger a message when the underlying class is used without the service. In case your application uses classes directly, don't forget to add the deprecation messages to the classes too.

The new deprecated option is so convenient, that Symfony itself uses it to deprecate some services. For example:

1
2
3
4
5
6
7
<!-- src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml -->
<service id="security.context" class="%security.context.class%">
        <argument type="service" id="security.token_storage" />
        <argument type="service" id="security.authorization_checker" />
        <deprecated>The "%service_id%" service is deprecated since Symfony 2.6
                    and will be removed in 3.0.</deprecated>
     </service>
Published in #Living on the edge