Before I start explaining how to use the registry classes defined in the previous installment of the series, I’d like to spend some time reintroducing their corresponding definitions. The first of these classes, remember, was abstract. It was responsible for defining the structure and encapsulating most of the functionality of a generic registry. Here it is: (RegistryAbstract.php) abstract class RegistryAbstract { protected static $_instances = array();
// get Singleton instance of the registry public static function getInstance() { // the static call to 'getClass()' is resolved at runtime $class = static::getClass(); if (!isset(self::$_instances[$class])) { self::$_instances[$class] = new $class; } return self::$_instances[$class]; }
// throw an exception as this class can't be instantiated protected static function getClass() { throw new RegistryException('This class is abstract and cannot be instantiated!'); }
// implemented by registry subclasses abstract public function set($key, $value);
// implemented by registry subclasses abstract public function get($key);
// implemented by registry subclasses abstract public function clear(); } (RegistryException.php) <?php class RegistryException extends Exception{} Aside from declaring some abstract getters and mutators, undeniably the most important aspect of the previous “RegistryAbstract” class is the implementation of its Singleton “getInstance()” method. This method uses the functionality of late static bindings to resolve at run time which instance to return according to the scope from which it’s called. For obvious reasons, its invocation from the abstract parent will throw an exception; however, things are quite different when the method is called from a concrete subclass, like the one defined below: (ArrayRegistry.php) <?php class ArrayRegistry extends RegistryAbstract { private $_data = array();
// save data to the registry public function set($key, $value) { $this->_data[$key] = $value; return $this; }
// get data from the registry public function get($key) { return isset($this->_data[$key]) ? $this->_data[$key] : null; }
// get called class public static function getClass() { return __CLASS__; } // clear the registry public function clear() { $this->_data = array(); } } As you can see, this array-based registry class not only inherits the “getInstance()” Singleton defined by its parent, but it also implements its own version of the static “getClass()” method. This process allows it to return an instance of this registry to client code. So far, you've seen how these classes use LSB to resolve calls to static methods at run time. As I expressed at the beginning, though, the goal here is to set up an example that puts these classes to work in tandem. The example will be created in the section to come, so click on the link that appears below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|