HomePHP An Introduction to Using the Decorator Pattern with PHP
An Introduction to Using the Decorator Pattern with PHP
A decorator class allows you to add more capacity to an existing class while leaving the original class untouched. It has certain advantages over inheritance, as you will learn in this first article of a three-part series.
Among the plethoric variety of design patterns that can be applied in software engineering, there are a few that are specifically interesting for web developers. These feature potentially easy implementation and versatility, particularly when working with object-oriented applications. Speaking more specifically, the Decorator pattern is one that I found myself using quite frequently inside my PHP-driven applications, in cases where I needed to construct a "bridging" class that was capable of extending the operability and functionality of a base class, but without having to introduce changes in its original structure.
Does that sound a little bit complex? Well, fear not; let me point you in the right direction. A "decorator" class is one that allows you to add more capacity to an existing class, by using some intermediate methods, while leaving the original class untouched. Okay, you have every right to say that the same result can be achieved by using inheritance, and then creating some cool subclasses. However, in that case you'd be working with objects of the same type, while a "decorator" object belongs to a completely different family. Are you getting my point now? I bet you are.
Indeed, one of the most appealing aspects of the decorator design pattern is the ease with which you can use a class of different type to extend the capabilities of another. Of course, this isn't always the best course of action to take, simply because it can be much easier to modify the original class by using inheritance, but there are situations where a decorator class can find its place inside an application.
Due to the wide range of web applications where the decorator pattern can be successfully applied, over the course of this series, I'll show you some useful pointers to demonstrate how this pattern works, and how it can be introduced in your own PHP applications with only minor hassles. Before you start reading the rest of this article, make sure that you have a pretty good understanding of object-based programming with PHP, since you'll see an abundance of material related to this topic.
Having introduced the basics of the decorator pattern, let's learn how it can be applied to PHP with several practical examples. Let’s get started!