I am new to Symfony. I read about service decoration but I don't still understand it. What does it actually mean to decorate a service in Symfony?
Symfony service decoration, what does it actually mean?
301 views Asked by Templator Khan At
2
There are 2 answers
0
On
In Symfony, a decorator service is a design pattern used in service container configuration to modify or extend the behavior of an existing service without modifying its original code.
Here is an article explaining symfony decorator with an example.
https://medium.com/@rcsofttech85/decorator-services-in-symfony-045ed126ab10
IMO, decoration is an awesome POO pattern that allows you to change (decorate) the behavior of a third party. In Symfony, this is useful to change the behavior of third-party services (bundles essentially).
As Cerad mentions it in comments, you might want to start by looking up the decoration pattern if you didn't understand the Symfony documentation. Symfony doc explains how to use it, but the concept isn't explained.
If you're searching a good example, I recommend you this Symfonycast tutorial: Ryan explains how he's using the decoration pattern to change the behavior of the Api-Platform State Provider. In this tutorial, Ryan need an DTO resource, but the original item provider returns an entity. Ryan use the decoration pattern to change the behavior. Because of the declaration in
services.yamlfile, Symfony will call the decorator service instead of the original one. In hisprovidemethod (the methods that decorates the original one), Ryan call the originalprovidemethod, but instead of returning the Entity, he maps it to a DTO resource, then he returns this result.