HomePHP Late Static Bindings in PHP 5.3 with the Abstract Factory Pattern
Late Static Bindings in PHP 5.3 with the Abstract Factory Pattern
In this fourth part of the series, I demonstrate how Late Static Bindings can be useful for implementing the abstract factory design pattern. The feature will be used at the instance level within the constructor of an abstract factory class, where at least one of its concrete implementations is tasked with factoring a couple of block-level (X)HTML objects, such as divs and paragraphs.
Among the new features that have been packaged with PHP 5.3, thereís one that turns out to be remarkably useful during the development of object-oriented applications. It allows programmers to efficiently solve common issues that occur when itís necessary to deal with hierarchies of classes in a static context.
Yes, as you may already have guessed, in this case Iím talking about Late Static Bindings (LSB), which can be used for determining at runtime from which class a static method has been called. Itís possible, however, that youíre wondering what the big deal is, right?
Well, Iím glad you asked! While at first glance this ability seems to have little or no importance, especially when compared to other widely-marketed improvements added to the language (such as native namespaces and anonymous functions), LSB are actually a handy enhancement that makes it considerably easier to create flexible hierarchies of classes.
To illustrate how helpful LSB can actually be in a concrete use case, in previous parts of this series I showed how to use them to build a couple of basic, yet functional, registry classes. The first of these classes was an abstract one that implemented a static Singleton method called ďgetInstance(),Ē while the second class was a simple array-based registry derived from the corresponding abstract parent. This hierarchy normally wouldnít be especially interesting, but thanks to the functionality of LSB, the above-mentioned method returned to client code (when possible) an instance of the class from which it was invoked. Not too bad, huh?
In addition, I showed how to replicate the previous hierarchy by using the ďget_called_class()Ē function, available since PHP 5.3.0, thus simplifying the definitions of the classes involved. Nonetheless, itís fair to stress that the use of LSB isnít limited to facilitating the implementation of the registry pattern in static environments. They can be utilized at the instance level as well. Therefore, in this fourth installment of the series Iím going to demonstrate how to take advantage of this capability by constructing an abstract factory class whose concrete implementations will be responsible for creating a few HTML widgets.
Are you feeling eager to see how this will be done? Then donít hesitate; start reading!