The Registry Pattern
I often use several design patterns in my scripts, and this is one of my favorites: The registry pattern.
If you use a lot of classes, I bet you came around the problem you want to share an object with another class.
One solution is, to use the Singleton design pattern. But if you have a lot of classes, this is not really efficient. This is were the registry comes in. It's a class where you can store and retrieve variables.
To view an example, click the 'Read more' link.
The class I use for this site is the following:
- /**
- * Registry Class
- *
- * Holds all objects, so the objects are accesible everywhere
- */
- class Registry
- {
- protected $values;
- /**
- * Singleton, returns the instance of this class
- * @return Registry
- */
- {
- if(self::$instance == null)
- {
- self::$instance = new Registry();
- }
- return self::$instance;
- }
- /**
- * Private constructor for Singleton, inits some vars
- */
- private function __construct()
- {
- }
- /**#@+
- * Operator overloading functions
- * */
- public function __get($name)
- {
- if($this -> Exists($name))
- {
- }
- }
- public function __set($name, $value)
- {
- $this -> Register($value, $name);
- }
- public function __unset($name)
- {
- $this -> unregister($name);
- }
- public function __isset($name)
- {
- return $this -> exists($name);
- }
- /**#@-*/
- /**
- * Get a loaded class
- * @param string $name The name from the class loaded, or a name you gave
- * @return object
- */
- public function Retrieve($name)
- {
- if($this -> exists($name))
- {
- }
- else
- {
- throw new Exception('Class '.$name.' does not exists');
- }
- }
- /**
- * Register an object
- * @param mixed $object The object to register
- * @param string $name Optional, a custom name (default the class name)
- */
- public function Register($object, $name = '')
- {
- {
- if($name == '')
- {
- }
- }
- }
- /**
- * Unregister an object
- * @param string $name the class name
- */
- public function Unregister($name)
- {
- {
- }
- }
- /**
- * Checks if a certain class is loaded
- * @param string $name The class name
- * @return bool
- */
- public function Exists($name)
- {
- }
- }
It's very simple: The class has one protected member, an array where all objects will be stored in.
The function Register is used for storing an object in the registry, the Unregister function is used for deleting an object.
And to retrieve an object, you can use the function Retrieve.
I also added some of the PHP operator overloading functions, so you can use:
- $registry -> member -> Call();
instead of
- $object = $registry -> Retrieve('member');
- $object -> Call();
Well, that's it for today.

