HomePHP Introducing the Flyweight Pattern with PHP 5
Introducing the Flyweight Pattern with PHP 5
Among the considerable variety of structural design patterns that can be implemented with PHP 4 (and PHP 5, by the way), thereís one in particular that deserves special attention. It's easy to apply in the context of a given web application, and it offers remarkable functionality when it comes to preventing the unnecessary instantiation of different classes. This two-part series covers that pattern.
Naturally, if you already read the title of this series, then youíll know that Iím speaking specifically of the flyweight pattern. But before I go into further explanations, let me tell you briefly how this pattern works. This will give you a better idea of how and when it can be used.
In simple terms, when the flyweight pattern is applied, itís possible to specify programmatically that a particular class is going to have only a predefined number of instances, which are shared within the same implementation. This simple concept itself introduces an immediate benefit: it prevents unnecessary instantiations of the class in question across the same application, which results in a noticeable improvement in the performance of certain systems that must work with heavy loads.
Certainly, if you reread the above definition, itís clear to see that a flyweight class can be considered a straightforward approach to keep the creation of objects carefully balanced. This can improve the web serverís overall performance, as I mentioned a few lines above.
Nonetheless, this series isnít limited to introducing boring theory on how the flyweight pattern works. You'll have the chance to learn and test many practical examples related to the referenced pattern, so you can quickly start applying it in your own PHP applications.
A final note before I proceed further: all the examples that youíll see here will be developed with PHP 5, but they can be easily modified to work with PHP4 as well.
Having clarified that point, letís find out together how to implement flyweight classes with PHP. Itís going to be instructive and fun!