HomePHP Introducing the Composite Pattern in PHP 5
Introducing the Composite Pattern in PHP 5
The composite pattern is one of the less commonly used patterns in PHP 5. Nevertheless, in certain situations, it is very helpful. This article, the first one in a two-part series, will introduce you to the basic concepts of the composite pattern.
In the vast and definitely fascinating terrain of pattern-based application development with PHP, quite possibly you'll know that there are certain patterns that are much simpler to implement than others. Actually this fact is a logical consequence of having acquired a strong background in the most common ones.
It's highly probably that you already have a solid knowledge of some familiar topics that belong specifically to software engineering, such as what a Singleton is, or how a concrete factory class can be created with PHP by a few easy steps.
However, while there are specific design patterns that are indeed used by many developers on a frequent basis during the development of different PHP applications, the truth is that there's a small group of them that very often remain unexplored, either because they simply can't be applied so quickly in real world situations, or because of their rather complex implementation.
So, considering the fact that this limited set of uncommon design patterns can be potentially interesting to you (and to me, by the way), and taking into account that they do deserve at least a quick look, in this two part series I'm going to teach you how to implement the composite pattern with PHP 5.
Just in case this pattern doesn't ring any bells to you, let offer you a quick introduction to how it works. In crude terms, when the composite pattern is applied in the context of a given application, one single object or a group of these objects will expose a nearly identical behavior. In other words, this means simply that it's possible to build a class in such a way that it will be capable of returning to client code the same output, regardless of whether the class in question works with one or with multiple objects. Sounds really interesting, isn't it?
Naturally, in this case I'm aware of the high level of abstraction that the composite pattern intrinsically possesses, therefore over the course of these two tutorials, I'm going to demonstrate how this pattern works by setting up numerous code samples, which surely will help understand the topic more clearly.
Having introduced quickly a basic definition on the composite pattern, let's move on and see how it can be implemented in PHP 5. The journey is going to be really educational, trust me, so let begin right now!