Skip to content

Instantly share code, notes, and snippets.

@MarcTowler
Created April 1, 2012 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MarcTowler/2279456 to your computer and use it in GitHub Desktop.
Save MarcTowler/2279456 to your computer and use it in GitHub Desktop.
<?php
class Registry {
/**
* @var array The store for all objects
*/
static private $store = array();
/**
* Add an object to the registry
*
* If you do not specify a name the class name is used
*
* @param mixed $object The object to store
* @param string $name Name used to retrieve the object
* @return mixed If overwriting an object, old one is returned
* @throws Exception
*/
static public function add($object, $name = null)
{
//Use the class name if not given, simulates singleton
$name = (!is_null($name)) ? $name : get_class($object);
//$name = strtolower($name);
$return = null;
if(isset(self::$store[$name]))
{
$return = self::$store[$name];
}
self::$store[$name] = $object;
return $return;
}
/**
* Get an object from the registry
*
* @param string $name Object name, {@see self::set()}
* @return mixed
* @throws Exception
*/
static public function get($name)
{
if(!self::contains($name))
{
throw new Exception("Object does not exist in registry");
}
return self::$store[$name];
}
/**
* Check if an object is in the registry
*
* @param string $name Object name, {@see self::set()}
* @return bool
*/
static public function contains($name)
{
if(!isset(self::$store[$name]))
{
return false;
}
return true;
}
/**
* Remove an object from the registry
*
* @param string $name Object name, {@see self::set()}
* @returns void
*/
static public function remove($name)
{
if(self::contains($name))
{
unset(self::$store[$name]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment