Example of the decorator pattern implementation done in PHP
The Decorator Pattern was original presented by Erich Gamma, Richard Helm, Ralph Johnson e John Vlissides in their book called Design Patterns: Elements of Reusable Object-Oriented Software.
This book is also known with the title Gang of Four GoF because of the authors number.
The book presents many Design Patterns which are very useful to developement challeges, by using solution which make the code more flexible and easy to mantain.
The Decorator pattern solves the problem of dynamically and flexibly extending object functionalities without modifying their source code. It is beneficial when dealing with a set of base classes, each with basic functionality, and the goal is to add or modify behavior independently and in a combinable way.
-
Extension Without Direct Modifications: Extend object functionalities without directly modifying the base class, avoiding potential side effects.
-
Flexible Composition: Allows flexible composition of additional behaviors by combining different decorators in various ways.
-
Open/Closed Principle: Follows the Open/Closed principle, allowing classes to be open for extension but closed for modification.
-
Maintaining Cohesion: Avoids the need to create numerous subclasses for handling all possible combinations of functionalities. Instead, functionalities can be flexibly combined through decorator composition.
-
Component Interface: Define a base interface (Component) with the basic set of operations.
-
Concrete Component: Implement the Component interface with a concrete class providing the core functionality.
-
Decorator Interface: Create a decorator interface mirroring the Component interface, serving as a blueprint for concrete decorators.
-
The Decorator Interface could be even an abstract class in PHP, in this way it is possible to add not only methods, but also properties to the interface.
-
Concrete Decorators: Develop concrete decorator classes that extend the Decorator interface, adding new functionalities or modifying existing ones.
-
Composition: Objects are composed by wrapping them with decorators. Decorators contain instances of the Component interface and can add their own behavior before or after delegating to the component they decorate.
To delve deeper into design patterns, including the Decorator Pattern, consider exploring the seminal book:
- "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (often referred to as the Gang of Four): Read Online
For an online reference on design patterns and the Decorator Pattern, you may find the following resource useful:
- Head First Design Patterns - A book that presents design patterns in a more accessible and reader-friendly manner.
Feel free to explore these resources to deepen your understanding of design patterns and their applications.


