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!