In case you haven't read the article that precedes this one, where I showed how the clever use of LSB in the object scope permits you to build more versatile and flexible factory classes, below I reintroduced the definitions of these sample classes. First, here’s the source code of the parent abstract factory, which looks like this: (HtmlElementFactory.php) <?php abstract class HtmlElementFactory { private $_element;
// constructor (Late Static Bindings are used at instance level) public function __construct($element = '', array $options = array()) { if ($element !== '') { $this->_element = static::create($element, $options); } }
public function getElement() { return $this->_element; }
// implemented by concrete factory classes public static function create($element, array $options = array()) { throw new HtmlElementFactoryException('This is an abstract factory and it does not create any concrete HTML element.'); } } (HtmlElementFactoryException.php) <?php class HtmlElementFactoryException extends Exception {} To be frank, understanding the logic driving this abstract factory is a pretty straightforward process. All this class does is use LSB within its constructor to call its static “create()” method at runtime. For obvious reasons, when invoked from this abstract class, the method will raise a custom exception. However, things become much more interesting when the method is called from the following concrete factory: (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); } } } As you can see, the above class now uses the “create()” method to return to client code two predefined block-level (X)HTML objects, which in this case happen to be divs and paragraphs. So what makes this factory so special? Well, thanks to the inherited constructor, the factory is capable of creating the aforementioned objects at instance level by means of the constructor and statically via “create()” method as well. That’s pretty good, right? Now that you understand how the usage of LSB in the object scope can be of great help when building flexible factories, it’s time to start defining the classes that will be responsible for originating the corresponding (X)HTML objects. Precisely, the first of these classes will be discussed in the section to come, so click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|