Some Terms: Registry Pattern, object hash

I would talk about a pattern whose name I fail to know before, giving it the name of multi-singleton.

Registry pattern

I read about it in PHP 5 certification study guide from php|architect’s series. This is the example given:

class Registry {
  private static $_register;
  public static function add(&$item, $name = null)
  {
    if (is_object($item) && is_null($name)) {
      $name = get_class($item);
    } elseif (is_null($name)) {
      $msg = "You must provide a name for non-objects";
      throw new Exception($msg);
    }
    $name = strtolower($name);
    self::$_register[$name] = $item;
  }
  public static function &get($name)
  {
    $name = strtolower($name);
    if (array_key_exists($name, self::$_register)) {
      return self::$_register[$name];
    } else {
      $msg = "’$name’ is not registered.";
      throw new Exception($msg);
    }
  }
  public static function exists($name)
  {
    $name = strtolower($name);
    if (array_key_exists($name, self::$_register)) {
      return true;
    } else {
      return false;
    }
  }
}

Simple enough, also I would like to talk about a function:

spl_object_hash($object)

This return an hash from an object. And now, more simply, I have a singleton, which I use to get info about an account, but also I want to use that class to give me info given an object. Thus:

class MySingleton {
  static private $instance = null;
  static private $_obj_register = array();
  static public function getInstance() {
    if(self::$instance == null) {
      $c = __CLASS__;
      self::$instance = new $c;
    }
    return self::$instance;
  }
  
  public function getInfoForNode($node) {
    $hash = spl_object_hash($node);
    if(!array_key_exists($hash, MySingleton::$_obj_register)) {
      // something to calc from $node and other singleton datas
      // ....
      // and store in array
      self::$_obj_register[$hash] = $node->nid;
    }
    return self::$_obj_register[$hash];
  }
}

I mixed the two, and dynamic method refer to static property.

Refer

Php|architect’s Zend PHP 5 Certification Study Guide Pro PHP: Patterns, Frameworks, Testing & More: Patterns, Frameworks, Testing and More

From Amazon.it

PHP]Architect’s Zend PHP 5 Certification Study Guide Pro PHP: Patterns, Frameworks, Testing and More

kindle!

Pro PHP: Patterns, Frameworks, Testing and More


Posted

in

,

by

Tags: