What is the Decorator pattern in PHP?
Why Interviewers Ask This
Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.
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.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What is PHP's memory management and how to optimize it?
Next
What is the Repository pattern in PHP?