Considering that the constructor of the earlier abstract factory class will invoke the static “create()” method at runtime due to the internal use of Late Static Bindings, building a concrete factory that returns to client code a couple of block-level (X)HTML objects is as simple as defining the following class: (BlockLevelElementFactory.php)
<?php
class BlockLevelElementFactory extends HtmlElementFactory { // create a block-level HTML element public static function create($element, array $options = array()) { if ($element === 'Div' or $element === 'Paragraph') { return new $element($options); } } } Mission accomplished. At this point, I created a simple, yet functional, concrete factory class which overrides the static “create()” method defined by its abstract parent. In this case, the method is responsible for factoring (X)HTML objects of type “Div” and “Paragraph” respectively, but naturally it’s possible to extend its functionality by adding support for other block-level objects. Nonetheless, the most interesting facet of this class is its ability to factor the objects either statically or through its constructor. This shows how useful Late Static Bindings actually are, even when used in the object scope. And with this final code sample I’m finishing this chapter of the series. As usual, feel free to tweak the source code of all the classes shown in this tutorial. Doing so will help you to better understand how to incorporate the functionality provided by LSB into your own object-oriented PHP applications. Final thoughts That’s it for the moment. Over this fourth part of the series, I demonstrated how Late Static Bindings can be quite useful when it comes to implementing the abstract factory design pattern. In the above code samples, this feature was used at the instance level within the constructor of an abstract factory class, where at least one of its concrete implementations was tasked with factoring a couple of block-level (X)HTML objects, such as divs and paragraphs. Of course, the next logical step we must take is to define the classes responsible for creating the aforementioned (X)HTML objects. That’s exactly the topic that I plan to cover in the forthcoming tutorial of the series. Now that you know what to expect from the next installment, you don’t have any excuses to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|