From the course: PHP: Design Patterns

Introducing the decorator pattern - PHP Tutorial

From the course: PHP: Design Patterns

Start my 1-month free trial

Introducing the decorator pattern

- When most people think of the Decorator Pattern, they only think of templating or rendering HTML, but they can be used for so much more. But before we dive into how we solve the problem, let's talk about the problem itself. When we think of good object-oriented design principles, one of the first that comes to mind is inheritance. We can add new behaviors to classes by extending the class and implementing what we need. Unfortunately, many languages, PHP included, only support single inheritance, which means A can extend B, but A can't extend both B and C. Now, what if we only need certain objects to have a behavior but not the entire class itself? It turns out, this is relatively easy with the Decorator Pattern. This pattern allows us to add new behavior at run time to specific instances of an object, instead of the entire class itself. The most common place this is used is in templating systems. It's easy to take an object and load it into a formatting or template object, and transform it for presentation. You end up with a nice separation of concerns while still getting the behaviors you need. But there's a downside to using decorators. Since they add behaviors at run time and it's not specific to the class itself, testing can be hard. Instead of just loading an object and validating a few properties, you have to create the correct base object, load it into the actual decorator object, and then test those results. Technically, this gets pretty far away from regular unit testing because we are testing the interactions between these objects, but we can still do it. Regardless, this is not an excuse to not test what you're building. You just have to be a little more thoughtful in how it works. Of course, all this makes way more sense when we make it concrete, so let's do that now.

Contents