PHP: Using a Registry

January 27, 2009

Over that last dozen or so projects I have worked on I have noticed that files containing settings, and other site specific data, tend to grow pretty quickly. Each time I open a settings file I struggle with the thought, ‘Do I use a define or a global variable?’. I do not really like using either. So today as I was working on a project I pondered yet again a via alternative. I decided to take a leap and build myself a registry type object. All this object does is store key value pairs. Really nothing more than a fancy associative array, but it gets the job done. I was still a bit nervous when I started actually implementing it. I almost chucked it, but I steeled myself and decided to at least finish it and see how it works with this project. So far using a registry has made it a ton easier to keep track of site configs. I no longer wonder how to store a config, I simply toss it in the registry. Everything has access to the registry so my settings are still just a few characters away. Here is the current registry class I am using. Simple for now, though it may expand as I find it useful. Note that the class is only partially phpdoc’d. By the end of this project it will be completely documented and reposted.

/**
 * Singleton. Use Registry->GetRegistry
 **/
class Registry {

	/**
	* Holds whether a registry exists already or not.
	*
	* @var Boolean
	*/
	private static $Exists = FALSE;

	/**
	 * Holds the info
	 *
	 * @var Array
	 **/
	private $Registry; 

	/**
	 * Default constructor
	 *
	 * Sets up some normal defaults for the cms
	 **/
	private function __construct() {
		// Paths - PLEASE APPEND WITH /
		$this->Set('path_library', 'lib/');
		$this->Set('path_controllers', 'controllers/');
		$this->Set('path_views', 'views/'); // Smarty needs this
		$this->Set('path_cache', 'cache/'); // Smarty needs this

		// Smarty Specific
		$this->Set('smarty_cache_enabled', true);
		$this->Set('smarty_cache_life', 3600); // 1 hour in seconds
		$this->Set('smarty_debugging', false);

		// Http links
		$this->Set('http_link', $_SERVER['SERVER_NAME']);

		// Misc
		$this->Set('default_controller', 'home'); // Default controller

	}

	public function GetRegistry() {

		if(!self::$Exists) {
			self::$Exists = new Registry();
		}

		return self::$Exists;
	}

	public function Set($Var, $Value) {
		$this->Registry[$Var] = $Value;
	}

	public function Get($Var) {
		return $this->Registry[$Var];
	}
} // end class
?>