Class registry
Posted: Wed Aug 08, 2007 7:39 am
feyd | Please use
feyd | Please use
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Does anyone has implemented a registry mechanism in PHP 4 that will allow me to register my objects and use them when i need them, something similar like this:Code: Select all
<?php
class Library_Registry {
/**
* Object registry provides storage for shared objects
* @var Library_Registry
*/
static $_registry = array();
/**
* offsetSet stores $newval at key $index
*
* @param mixed $index index to set
* @param $newval new value to store at offset $index
* @return void
*/
function register($name, $obj)
{
if (!is_string($name)) {
die('First argument $name must be a string.');
}
// don't register the same name twice
if (array_key_exists($name, self::$_registry)) {
die("Object named '$name' already registered. Did you mean to call registry()?");
}
// only objects may be stored in the registry
if (!is_object($obj)) {
throw new Zend_Exception("Only objects may be stored in the registry.");
}
$e = '';
// an object can only be stored in the registry once
foreach (self::$_registry as $dup=>$registeredObject) {
if ($obj === $registeredObject) {
$e = "Duplicate object handle already exists in the registry as \"$dup\".";
break;
}
}
/**
* @todo throwing exceptions inside foreach could cause leaks, use a workaround
* like this until a fix is available
*
* @link http://bugs.php.net/bug.php?id=34065
*/
if ($e) {
die($e);
}
self::$_registry[$name] = $obj;
}
/**
* registry() retrieves the value stored at an index.
*
* If the $index argument is NULL or not specified,
* this method returns the registry object (iterable).
*
* @see register()
* @param string $index The name for the value.
* @return mixed The registered value for $index.
*/
function registry($name=null)
{
if ($name === null) {
$registry = array();
foreach (self::$_registry as $name=>$obj) {
$registry[$name] = get_class($obj);
}
return $registry;
}
if (!is_string($name)) {
die('First argument $name must be a string, or null to list registry.');
}
if (!array_key_exists($name, self::$_registry)) {
die("No object named \"$name\" is registered.");
}
return self::$_registry[$name];
}
/**
* Returns TRUE if the $index is a named value in the
* registry, or FALSE if $index was not found in the registry.
*
* @param string $index
* @return boolean
*/
public function isRegistered($name)
{
return isset(self::$_registry[$name]);
}
}feyd | Please use
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]