Well I am trying to design a registry class for my project. The Registry class itself is pretty much a singleton class, it stores certain objects that can be retrieved and used in any scope of application. What differentiates this registry class from other available framework's is that my registry class stores system objects upon instantiation. It proves to be somewhat of a challenge to me since my programming skills aint that advanced yet. Here's the code I have so far:
class Registry extends ArrayObject{
// The registry class used to store objects available for entire application
protected $reserved = array("system", "path", "database", "cookies", "session", "currentuser", "usergroup", "settings", "page", "template", "request", "input", "action", "plugin", "debug");
protected static $instance;
public function __construct($props = ""){
// Construct the Registry object
$flags = parent::ARRAY_AS_PROPS;
if($props instanceof System) $props = self::initialize($props);
if(!is_array($props)) $props = array($props);
parent::__construct($props, $flags);
}
protected static function initialize($system){
// Initialize the Registry Object with basic properties
$init = array("system" => $system,
"path" => $system->path,
"database" => $system->db,
"cookies" => $system->cookies,
"session" => $system->session,
"currentuser" => $system->user,
"usergroup" => $system->usergroup,
"settings" => $system->settings,
"page" => $system->page,
"template" => $system->template,
"request" => $system->request,
"input" => $system->input,
"plugin" => $system->plugin,
"debug" => $system->debug);
return $init;
}
public static function getinstance(){
// Return all objects assigned in the registry singleton class
if(!self::$instance) self::instance = new Registry();
return self::$instance;
}
public static function assign($key, $val, $overwrite == TRUE){
// Assign objects to registry in class member methods
if($overwrite == FALSE and self::$instance->exist($key) == TRUE) throw new Exception("Cannot overwrite registered object");
else self::$instance->offsetSet($key, $val);
}
public static function retrieve($key){
// Retrieve objects from registry in class member methods
if(!self::$instance->exist($key)) throw new Exception("Cannot retrieve an unregistered object");
return self::$instance->offsetGet($key);
}
public static function remove($key){
// Remove objects in registry from class member methods
if(!in_array($key, $reserved)) self::$instance->offsetUnset($key);
}
public function exist($key){
return array_key_exists($key, $this);
}
public function clear(){
// Unset all registered objects, except for system objects
foreach(self::$instance as $key => $val){
self::remove($key);
}
}
}
So I borrowed some ideas from Zend Framework's Registry class, which extends the ArrayObject parent class to make it iterable. Please take a look at this class I designed and lemme know what problems you see from it. I'd appreciate comments and criticism very much.
Lord Yggdrasill