A while ago, I covered The Observer Pattern, a really useful pattern, particularly when it comes to event-handling systems.
Today, I’m going to take a look at the Composite Pattern, another really useful pattern that allows you to treat individual objects and collections of those objects as if they were the same. That may sound a little strange, but we’ll look at a concrete example, which should help clarify things: a List-based system.
The Observer Pattern is probably one of my favourite patterns.
It’s fairly straightforward, flexible, and best of all, the base classes you need to implement the Observer Pattern are available in the Standard PHP Library, so it should be available to all PHP5 applications.
Let’s jump straight in, and take a look at a possible scenario where we could use this pattern.
At the recent PHP UK Conference in London, one speaker described the Singleton Pattern as being evil. The main point brought up was that it brought global variables in through the back door, including all the problems associated with them.
Well, this is true, but only to a point. Just like eating ice-cream or junk food all the time would be bad for you, so would relying on the Singleton Pattern. However, it is still a very good pattern when used in specific instances, and when used sparingly, with discipline.
So, when could we consider using it?