🐘 PHP Advanced

What is the Decorator pattern in PHP?

Answer

The Decorator pattern dynamically adds behavior to objects by wrapping them in decorator classes that implement the same interface. The decorator delegates the core work to the wrapped object and adds its own behavior before or after. PHP example: a Logger interface, a FileLogger implementation, and a TimestampLogger decorator that wraps any Logger and prepends timestamps. $logger = new TimestampLogger(new FileLogger("app.log"));. Multiple decorators can be chained: new JsonLogger(new FilterLogger(new FileLogger($path))). PHP's stream wrappers, middleware stacks in frameworks (PSR-15), and pipeline patterns are all implementations of the Decorator principle. It follows Open/Closed principle — adding behavior without modifying existing classes.