Skip to content

Instantly share code, notes, and snippets.

@djcowan
Forked from dshafik/Registry.php
Last active March 29, 2021 10:02
Show Gist options
  • Save djcowan/0a3fc2837b8c60067a35004e82319628 to your computer and use it in GitHub Desktop.
Save djcowan/0a3fc2837b8c60067a35004e82319628 to your computer and use it in GitHub Desktop.
<?php
class ClassRegistry {
/**
* @var array The store for all objects
*/
private array $store = [];
/**
* 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
* @TODO - Check Method and Param Type Declaration
*/
public function add(object $object, string $name = null)
{
// Use the class name if not given, simulates singleton
$name = (!is_null($name)) ? $name : get_class($object);
// TODO return or not to return that is the question
$return = null;
if(isset($this->store[$name]))
{
$return = $this->store[$name];
}
$return = $this->store[$name] = $object;
return $return;
}
/**
* Get an object from the registry
*
* @param string $name Object name, {@see self::set()}
* @return mixed
* @throws Exception
*/
public function get(string $name):object
{
if(!$this->contains($name))
{
throw new Exception("Object does not exist in registry");
}
return $this->store[$name];
}
/**
* Check if an object is in the registry
*
* @param string $name Object name, {@see self::set()}
* @return bool
*/
static public function contains(string $name):bool
{
if(!isset($this->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(string $name):void
{
if($this->contains($name))
{
unset($this->store[$name]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment