DataRegistry Class

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
XPerez
Forum Newbie
Posts: 1
Joined: Fri Jun 11, 2010 2:49 am

DataRegistry Class

Post by XPerez »

Helo everyone!

I have developed a singleton class to help me in developing and testing sites, because some times it's hard to discover errors and sometimes these errors are produced before a page re-load. Logging errors correctly must to be the safe form, but when you work with a lot of web apps, not all developers understand it.

The DataRegistry Class is similar to Zend_Registry, but more usefull, framework independent, and have more methods and functionality (persistence, namespaces), you can:

Save any type of data (string, array, object, file, numeric, boolean, etc)
Save data in separated namespaces
Save with or without persistence (data can be retrieved in next page load)
Save data by key (indexed arrays)
Get data anywhere
Add data to an array log (mysql commands, mysql execution times, errors, traces, debbug information, etc)
Test data. A simple command test if exists data
Clear data. Remove data from registry
Get data by key (indexed arrays)
Clear a key from data array (only clear an specific key from an indexed array)
Clear commands, only one line code.

Here the code:

Code: Select all

<?php
/**
 * Data_Registry
 *
 * NOTICE OF LICENSE
 *
 * This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *  
 *  Copyright (c) 2010 Xavier Perez (http://www.4amics.com/x.perez)
*/

/**
 * @category   Data_Registry
 * @package    Data_Registry
 * @copyright  Copyright (c) 2010 Xavier Perez (http://www.4amics.com/x.perez)
 * @license    http://www.gnu.org/copyleft/gpl.html  GNU GPL v.3
 * @author     Xavier Perez 
 * @version    1.0.8
 */

/**
 * Class Data_Registry
 *
 * Store and retrieve data 
 * @package     Data_Registry
 * 
 */
class Data_Registry
{
	/**
	* Global store of all namespaces and vars
	* @var array
	*/	
    private static $vars    = array();
	/**
	* Instance of each namespace
	* @var array
	*/	
    private static $instance = array();
	/**
	* Default namespace
	* @var string
	*/	
    private static $defaultnamespace = "default";
    /**
	* Current namespace used
	* @var string
	*/	
    private static $namespace = "";
	/**
	* Basename for namespaces
	* Provides a form to distinguish between datastorge variables and other variables 
	* @var string
	*/	
    private static $basenamespace = 'DR_';
	/**
	* Basename for session namespaces
	* The name of the main SESSION element to save all namespaces and vars
	* @var string
	*/	
    private static $sessionname = 'Data_Registry';
	/**
	* Global persistence
	* Enable or disable global persistence, by default, disabled
	* @var string
	*/	
    private static $gpersistent = FALSE;
	/**
	* Local persistence settings
	* Array to save specified settings for local persistence
	* @var array
	*/	
    private static $lpersistent = array();
    
    /**
    * Constructor, if there are global persistence, load data from store
    * 
    * Allows to restore namespace from SESSION automatically
    * 
    */
    private function __construct()
    {
    	if (self::$gpersistent === TRUE)
    	{
    		self::restoreNameSpace(TRUE);
    	}
    } 
    
    /**
    * Destructor, if there are persistence, save data in store
    * 
    * Allows to backup namespace in SESSION automatically
    * 
    */
    public function __destruct()
    {
    	foreach (self::$vars as $key => $val)
    	{
			if (self::$gpersistent === TRUE OR (isset(self::$lpersistent[$key]) && self::$lpersistent[$key] === TRUE))
			{
    			self::$namespace = $key;
    			self::backupNameSpace();
			}
    	}
    	self::$vars = array();
    } 
    
    /**
	* Load current pointer to given namespace
	*
	* @param  string  Namespace name
	*/
    public static function init($nameSpace="")
    {
    	// Set default is not specified
    	if ($nameSpace == "")
    		$nameSpace = self::$defaultnamespace;
    		 
    	// Assign current namespace used
		self::$namespace =self::$basenamespace.$nameSpace;
    	
		// Check exists current instance
		if (!isset(self::$instance[self::$namespace]))
			self::$instance[self::$namespace] = NULL;

		// Create new instance or return current
    	if (self::$instance[self::$namespace] == NULL)
			self::$instance[self::$namespace] = new self();

		return self::$instance[self::$namespace];
    }
    
    /**
	* Change persistent default
	*
	* @param  boolean Enable / disable persistence
	* @param  boolean Affects global persistence 
	*/
    public static function setPersistence($enable,$global=FALSE)
    {
    	if ($enable === TRUE OR $enable === FALSE)
    	{
	   		self::$lpersistent[self::$namespace] = $enable;
    		if ($global === TRUE)
    			self::$gpersistent = $enable;
    	}
    	if (isset(self::$instance[self::$namespace]))
    		return self::$instance[self::$namespace];
    	else
    		return NULL;
    }
    
    /**
	* Change session Name 
	* 
	* Call it before any other command
	* 
	* @param  boolean Enable / disable persistence
	* @param  boolean Affects global persistence 
	*/
    public static function setSessionName($name)
    {
    	self::$sessionname = $name;
    } 
    
    /**
	* Save persistence to session (TRUE) / or destroy SESSION namespace (FALSE)
	*
	* @param  boolean Backup (TRUE) or Delete backup (FALSE)
	*/
	public static function backupNameSpace($enable=TRUE)
    {
		if ($enable === TRUE)
		{
			$_SESSION[self::$sessionname][self::$namespace] = gzdeflate(serialize(self::$vars[self::$namespace]));
			self::$lpersistent[self::$namespace] = $enable;
		}
		if ($enable === FALSE && isset ($_SESSION[self::$namespace]))
		{ 
			unset($_SESSION[self::$sessionname][self::$namespace]);
			self::$lpersistent[self::$namespace] = $enable;
		}
    }
    
    /**
	* Get persistent data from current SESSION
	*
	* @param  boolean All namespaces (TRUE) on only current namespace (FALSE)
	*/
    public static function restoreNameSpace($all=FALSE)
    {
    	if ($all === FALSE)
    	{
    		if (isset($_SESSION[self::$sessionname][self::$namespace]))
    		{
    			self::$vars[self::$namespace] = unserialize(gzinflate($_SESSION[self::$sessionname][self::$namespace]));
    		}
    		unset($_SESSION[self::$sessionname][self::$namespace]);
    	}
    	else
    	{
			if (isset($_SESSION[self::$sessionname]))
			{
	    		foreach ($_SESSION[self::$sessionname] as $key => $val)
				{
					if (preg_match('/^'.self::$basenamespace.'/',$key))
					{				
						if (!isset(self::$vars[$key]))
			    		{
			    			self::$vars[$key] = unserialize($val);
			    		}
			    		unset($_SESSION[self::$sessionname][$key]);
					}
				}
			}
    	}
    }
    
    /**
	* Get data
	*
	* @param  string  Varname to get
	* @return string|integer|boolean|date|array   
	*/
	public static function get($var)
    {
    	$data = FALSE;
    	if (isset(self::$vars[self::$namespace][$var]))
    	{
			$data=self::$vars[self::$namespace][$var];
    	}
    	return $data;
    }
    
	/**
	* Get datakey
	*
	* @param  string  Varname to get
	* @param  string  Key to get
	* @return string|integer|boolean|date|array   
	*/
	public static function getKey($var,$key)
    {
    	$data = FALSE;
    	if (isset(self::$vars[self::$namespace][$var]))
    	{
			if (is_array(self::$vars[self::$namespace][$var]) && isset(self::$vars[self::$namespace][$var][$key]))
    			$data=self::$vars[self::$namespace][$var][$key];
    		if (is_object(self::$vars[self::$namespace][$var]) && isset(self::$vars[self::$namespace][$var]->{$key}))
    			$data=self::$vars[self::$namespace][$var]->{$key};
    	}
   		return $data;
    }
    
    /**
	* Get flash data
	*
	* Get a data and delete it from namespace
	* 
	* @param  string  Varname to get
	* @return string|integer|boolean|date|array   
	*/
	public static function getFlash($var)
    {
    	$data = FALSE;
    	if (isset(self::$vars[self::$namespace][$var]))
    	{
			$data=self::$vars[self::$namespace][$var];
    		if (isset($_SESSION[self::$namespace][$var]))
    			unset($_SESSION[self::$namespace][$var]);
			unset(self::$vars[self::$namespace][$var]);
    	}
    	return $data;
    }
    
	/**
	* Get flash datakey
	*
	* Get datakey and delete it from namespace
	* 
	* @param  string  Varname to get
	* @param  string  Key to get
	* @return string|integer|boolean|date|array   
	*/
    public static function getFlashKey($var,$key)
    {
    	$data = FALSE;
    	if (isset(self::$vars[self::$namespace][$var]))
    	{
			if (is_array(self::$vars[self::$namespace][$var]) && isset(self::$vars[self::$namespace][$var][$key]))
			{
    			$data=self::$vars[self::$namespace][$var][$key];
				unset(self::$vars[self::$namespace][$var][$key]);
			}
    		if (is_object(self::$vars[self::$namespace][$var]) && isset(self::$vars[self::$namespace][$var]->{$key}))
    		{
    			$data=self::$vars[self::$namespace][$var]->{$key};
				unset(self::$vars[self::$namespace][$var]->$key);
    		}
    		if (isset($_SESSION[self::$namespace][$var][$key]))
    			unset($_SESSION[self::$namespace][$var][$key]);
    	}
   		return $data;
    }
    
    /**
	* Set data
	*
	* @param  string  Varname to save
	* @param  string|integer|boolean|array  Data to save
	*/
    public static function set($var,$value)
    {
    	self::$vars[self::$namespace][$var] = $value;
    	return self::$instance[self::$namespace];
    }
    
    /**
	* Set datakey
	*
	* @param  string  Varname to save
	* @param  string  Key to save
	* @param  string|integer|boolean|array  Data to save
	*/
    public static function setKey($var,$key,$value)
    {
    	self::$vars[self::$namespace][$var][$key] = $value;
    	return self::$instance[self::$namespace];
    }
    
    /**
	* Add data
	*
	* @param  string  Varname array to add a new element
	* @param  string|integer|boolean|array  Data to save
	*/
    public static function add($var,$value)
    {
    	self::$vars[self::$namespace][$var][] = $value;
    	return self::$instance[self::$namespace];
    }

    /**
	* Test var
	*
	* @param  string  Varname to test
	* @return boolean   
	*/
	public static function test($var)
	{
    	if (isset(self::$vars[self::$namespace][$var]))
			return TRUE;
		else
			return FALSE;
	}
	
    /**
	* Test var key
	*
	* @param  string  Varname to test
	* @param  string  Key to test
	* @return boolean   
	*/
	public static function testKey($var,$key)
	{
    	if (isset(self::$vars[self::$namespace][$var][$key]))
			return TRUE;
		else
			return FALSE;
	}

    /**
	* Clear var
	*
	* @param  string  Varname to clear
	* @return boolean   
	*/
    public static function clear($var)
    {
    	if (isset(self::$vars[self::$namespace][$var]))
    	{
    		unset(self::$vars[self::$namespace][$var]);
    		return TRUE;
    	}
    	else
    		return FALSE;
    }
    
    /**
	* Clear var key
	*
	* @param  string  Varname 
	* @param  string  Key to clear
	* @return boolean   
	*/
    public static function clearKey($var,$key)
    {
    	if (isset(self::$vars[self::$namespace][$var][$key]))
    	{
    		unset(self::$vars[self::$namespace][$var][$key]);
    		return TRUE;
    	}
    	else
    		return FALSE;
    }

	/**
	* Clear namespace
	*
	* @return boolean   
	*/
    public static function clearNameSpace()
    {
    	if (isset(self::$vars[self::$namespace]))
    	{
    		unset(self::$vars[self::$namespace]);
    		if (isset($_SESSION[self::$namespace]))
    			unset($_SESSION[self::$namespace]);
    		return TRUE;
    	}
    	else
    		return FALSE;
    }
    
	/**
	* Get all vars in namespace
	*
	* @return array   
	*/
    public static function getNameSpace()
    {
    	if (isset(self::$vars[self::$namespace]))
    	{
    		return self::$vars[self::$namespace];
    	}
    	else
    		return FALSE;
	}

	/**
	* Get all namespaces
	*
	* @return array   
	*/
    public static function getAllNameSpaces()
    {
    	if (isset(self::$vars))
    	{
    		return self::$vars;
    	}
    	else
    		return FALSE;
	}
	
	/**
	* Set a class as an element of Data_Registry and get this class as new object
	* If exists current class, returns previous saved object
	*
	* @param  string  Classname 
	* @param  string  Prefix - allows to have copies of same class in Data_Registry
	* @return array   
	*/
	public static function getClass($class,$prefix="")
	{
    	if (!isset(self::$vars[self::$namespace][$class.$prefix]))
    		self::$vars[self::$namespace][$class.$prefix] = new $class();
    		
 		return self::$vars[self::$namespace][$class.$prefix]; 		
	}
	
	/**
	* Get list of vars saved for current namespace
	*
	* @return array   
	*/
	public static function listVars()
	{
		if (!isset(self::$vars[self::$namespace]))
			return array();
			
		$list = array();
		$index = 0;
		foreach (self::$vars[self::$namespace] as $key => $val)
		{
			$list[$index]["namespace"] 	= self::$namespace;
			$list[$index]["varname"] 	= $key;
			$list[$index]["vartype"] 	= gettype($val);
			$list[$index]["varpersist"] = isset(self::$lpersistent[self::$namespace])?self::$lpersistent[self::$namespace]:0||self::$gpersistent;
			$index++;
		}
		return $list;
	}

	/**
	* Get list of vars saved for all namespaces
	*
	* @return array   
	*/
	public static function listAllVars()
	{
		$list = array();
		$index = 0;
		foreach (self::$vars as $key => $val)
		{
			foreach ($val as $key2 => $val2)
			{
				$list[$index]["namespace"] 	= $key;
				$list[$index]["varname"] 	= $key2;
				$list[$index]["vartype"] 	= gettype($val2); 
				$list[$index]["varpersist"] = isset(self::$lpersistent[$key])?self::$lpersistent[$key]:0||self::$gpersistent;
				$index++;
			}
		}
		return $list;
	}

}
Here the test class to show how it works:

Code: Select all

<?php 
// Include a resusable (persistent) class to demonstrate example 15
// Any class to be reusable (persistent) must to be loaded BEFORE session_start
//	Here are the testclass code, instead of an include.
	class testClass { 	var $count = 0; function __construct() 	{ $this->count=0; } function sumCount() { $this->count ++; return $this; } function getCount()	{ return $this->count; 	} }


// Session_start needed to data persistence
	if(session_id() == "")
	{
		session_start();
	} 

include_once "Data_Registry.php";

// Base settings
//
// Assign name to the session var, all namespaces will be under this varname.
// 		Data_Registry::setSessionName('Data_Registry');
// Set global persistence ON
// 		Data_Registry::setPersistence(TRUE,TRUE);
// Set global persistence OFF
// 		Data_Registry::setPersistence(FALSE,TRUE);

// Example1
// SET single var
	echo "<b>Example 1 </b><br />";
	echo "Set a single data <br />";
	echo "<ul>Data_Registry::init()->set('Name','Alex');</ul>";
	Data_Registry::init()->set('Name','Alex');
	// GET
	echo "Result:<br />Name: ".Data_Registry::init()->get('Name');
	echo "<br /><br />";

// Example 2
// SET an array
	echo "<b>Example 2 </b><br />";
	echo "Set an array <br />";
	echo "<ul>Data_Registry::init()->set('Customer',array('Name' => 'Paul', 'Surname' => 'Smith'));</ul>";
	Data_Registry::init()->set('Customer',array('Name' => 'Paul', 'Surname' => 'Smith'));
	// GET an array
	echo "Customer data: ";
	var_dump(Data_Registry::init()->get('Customer'));
	echo "<br /><br />";

// Example 3
// SET in different nameSpace
	echo "<b>Example 3 </b><br />";
	echo "Set a single data in other namespace<br />";
	echo "<ul>Data_Registry::init(1)->set('Name','Xavier');</ul>";
	echo "<ul>Data_Registry::init('CONFIG')->set('DOMAIN',\$_SERVER['HTTP_HOST']);</ul>";
	Data_Registry::init(1)->set('Name','Xavier');
	Data_Registry::init('CONFIG')->set('DOMAIN',$_SERVER["HTTP_HOST"]);
	// GET
	echo "'Name' in default NameSpace: ".Data_Registry::init()->get('Name');
	echo "<br />";
	echo "'Name' in Namespace 1: ".Data_Registry::init(1)->get('Name');
	echo "<br /><br />";

// Example 4
// Dump current data in namespace default
	echo "<b>Example 4 </b><br />";
	echo "Dump data in namespace (default): ";
	echo "<ul>var_dump(Data_Registry::init()->getNameSpace());</ul>";
	var_dump(Data_Registry::init()->getNameSpace());
	echo "<br /><br />";

// Example 5
// Dump current data in namespace 1
	echo "<b>Example 5 </b><br />";
	echo "Dump data in namespace 1: ";
	echo "<ul>var_dump(Data_Registry::init(1)->getNameSpace());</ul>";
	var_dump(Data_Registry::init(1)->getNameSpace());
	echo "<br /><br />";

// Example 6
// CLEAR Data
	echo "<b>Example 6 </b><br />";
	echo "Clear Customer data: ";
	echo "<ul>Data_Registry::init()->clear('Customer');</ul>";
	echo "<ul>var_dump(Data_Registry::init()->get('Customer'));</ul>";
	Data_Registry::init()->clear('Customer');
	var_dump(Data_Registry::init()->get('Customer'));
	echo "<br /><br />";

// Example 7
// CLEAR NameSpace
	echo "<b>Example 7 </b><br />";
	echo "Clear Namespace <br />";
	echo "<ul>Data_Registry::init()->clearNameSpace();</ul>";
	Data_Registry::init()->clearNameSpace();
	echo "Name: ".Data_Registry::init()->get('Name');
	echo "<br /><br />";

// Example 8
// Dump current data in all namespaces
	echo "<b>Example 8 </b><br />";
	echo "Dump data in all namespaces : ";
	echo "<ul>var_dump(Data_Registry::init(1)->getAllNameSpaces());</ul>";
	var_dump(Data_Registry::init(1)->getAllNameSpaces());
	echo "<br /><br />";


// Example 9
// Checking exists data
	echo "<b>Example 9 </b><br />";
	echo "Check for a defined data <br /> ";
	echo "<ul>if (Data_Registry::init(1)->get('Name')?TRUE:FALSE == TRUE)</ul>";
	if (Data_Registry::init(1)->get('Name')?TRUE:FALSE == TRUE)
		echo "'Name' exists :".Data_Registry::init(1)->get('Name');
	else
		echo "'Name' not found";
	echo "<br /><br />";
	
// Example 10
// SET a key in an aray or object
	echo "<b>Example 10 </b><br />";
	echo "Change a key <br />";
	echo "<ul>Data_Registry::init()->set('Customer',array('Name' => 'Paul', 'Surname' => 'Smith'));</ul>";
	Data_Registry::init()->set('Customer',array('Name' => 'Paul', 'Surname' => 'Smith'));
	// GET an array
	echo "Customer data before Name change: ";
	var_dump(Data_Registry::init()->get('Customer'));
	// Change a key
	echo "<ul>Data_Registry::init()->setKey('Customer','Name','Peter');</ul>";
	Data_Registry::init()->setKey('Customer','Name','Peter');
	echo "<br />";
	// GET an array
	echo "Customer data after Name change: ";
	var_dump(Data_Registry::init()->get('Customer'));
	echo "<br /><br />";

// Example 11
// Concatenate setters
	echo "<b>Example 11 </b><br />";
	echo "Multiple SET <br />";
	echo "<ul>Data_Registry::init('DATA')->set('Data1','Value1')->set('Data2','Vaue2')->set('Data3','Value3');</ul>";
	Data_Registry::init('DATA')->set('Data1','Value1')->set('Data2','Vaue2')->set('Data3','Value3');
	var_dump(Data_Registry::init('DATA')->getNameSpace());
	echo "<br /><br />";

// Example 12
// Data persistence
// Manual persistence
	echo "<b>Example 12 </b><br />";
	echo "Data persistence <br />";
	echo "<ul>Data_Registry::init('SESSION')->restoreNameSpace();</ul>";
	// Restore not needed for automatic persistence, to enable automatic persistence, 
	//    change persistence in the main class, or change dinamically for a specific namespace: Data_Registry::$persistent=TRUE;
	Data_Registry::init('SESSION')->restoreNameSpace();
	Data_Registry::init('SESSION')->setPersistence(TRUE);
	$numVisits = Data_Registry::init('SESSION')->get('numVisits')+1;
	echo "Num visits: ".$numVisits."<br>";
	echo "<ul>Data_Registry::init('SESSION')->set('numVisits',$numVisits)->backupNameSpace();</ul>";
	Data_Registry::init('SESSION')->set('numVisits',$numVisits);
	echo "<br /><br />";

// Example 13
// Data persistence forced
// Manual persistence
	echo "<b>Example 13 </b><br />";
	echo "Enabling manual persistence <br />";
	// Enabling automatic persistence, allow to get SESSION namespace without the need to restore and save
	echo "<ul>Data_Registry::setPersistence(TRUE);</ul>"; 
	Data_Registry::init('PAGECONTROL')->restoreNameSpace();
	Data_Registry::init('PAGECONTROL')->setPersistence(TRUE);
	$kbsload = Data_Registry::init('PAGECONTROL')->get('kbsLoad');
	echo "Max memory ussage: current ".memory_get_usage()." max: ".$kbsload."<br>";
	echo "<ul>Data_Registry::init('PAGECONTROL')->set('kbsLoad',max($kbsload,memory_get_usage()));</ul>"; 
	Data_Registry::init('PAGECONTROL')->set('kbsLoad',max($kbsload,memory_get_usage()));
	// Disabling automatic persistence, destroy SESSION current namespace, but still allows access namespace before php finish this process. 
	// Data_Registry::setPersistence(FALSE);
	echo "<br /><br />";

// Example 14
// Adding data
	echo "<b>Example 14 </b><br />";
	echo "Add numeric indexed data <br />";
	echo "<ul>Data_Registry::init('DEBUG')->add('SQLDEBUG',array('SQL' => 'SELECT 1 FROM data','TIME' => '0.00112344'))</ul>";
	echo "<ul>Data_Registry::init('DEBUG')->add('SQLDEBUG',array('SQL' => 'SELECT 1 FROM otherdata','TIME' => '0.0027656'))</ul>";
	Data_Registry::init('DEBUG')->add('SQLDEBUG',array('SQL' => 'SELECT 1 FROM data','TIME' => '0.00112344'));
	Data_Registry::init('DEBUG')->add('SQLDEBUG',array('SQL' => 'SELECT 1 FROM otherdata','TIME' => '0.0027656'));
	echo "Retrieve data in DEBUG namespace : ";
	echo "<ul>var_dump(Data_Registry::init('DEBUG')->getNameSpace());</ul>";
	var_dump(Data_Registry::init('DEBUG')->getNameSpace());
	echo "<br /><br />";
		
// Example 15
// Saving an object
	echo "<b>Example 15 </b><br />";
	echo "Add or reuse an object <br />";
	echo "<ul>Data_Registry::init('CLASS_STORAGE')->getClass('testClass')->sumCount();</ul>";
	Data_Registry::init('CLASS_STORAGE')->restoreNameSpace();
	Data_Registry::init('CLASS_STORAGE')->setPersistence(TRUE);
	$testClass = Data_Registry::init('CLASS_STORAGE')->getClass('testClass')->sumCount();
	echo "Count in persistent mode inside a class<br />";
	echo "<ul>Data_Registry::init('CLASS_STORAGE')->getClass('testClass')->getCount();</ul>";
	echo "Count: ".Data_Registry::init('CLASS_STORAGE')->getClass('testClass')->getCount();
	echo "<br /><br />";

// Example 16
// Test a var
	echo "<b>Example 16 </b><br />";
	echo "Test a var <br />";
	echo "<ul>Data_Registry::init('CLASS_STORAGE')->test('Name');</ul>";
	echo "Test: ".Data_Registry::init('1')->test('Name');
	echo "<br /><br />";
	echo "<ul>Data_Registry::init('CLASS_STORAGE')->test('District');</ul>";
	echo "Test: ".Data_Registry::init('1')->test('District');
	echo "<br /><br />";
	
// Example 17
// Test a var
	echo "<b>Example 17 </b><br />";
	echo "Test a var key <br />";
	echo "<ul>Data_Registry::init()->testKey('Customer','Name');</ul>";
	echo "Test: ".Data_Registry::init()->testKey('Customer','Name');
	echo "<br /><br />";
	echo "<ul>Data_Registry::init()->testKey('Customer','District');</ul>";
	echo "Test: ".Data_Registry::init()->testKey('Customer','District');
	echo "<br /><br />";
	
// Example 18
// Load a file inside a varname
	echo "<b>Example 18 </b><br />";
	echo "Load this file (dr_examples.php) in persistence mode <br />";
	Data_Registry::init('FILES')->restoreNameSpace();
	Data_Registry::init('FILES')->setPersistence(TRUE);
	if (!Data_Registry::init('FILES')->test('Test'))
	{
		echo "<ul>Data_Registry::init('FILES')->set('Test',file_get_contents('dr_examples.php'));</ul>";
		Data_Registry::init('FILES')->set('Test',file_get_contents('dr_examples.php'));
	}
	echo "<ul>Data_Registry::init('FILES')->get('Test');</ul>";
	
	echo "<textarea rows='20' cols='100'>".htmlentities(Data_Registry::init('FILES')->get('Test'))."</textarea>\n";
	echo "<br /><br />\n";
	
// Example 19
// Get a list of vars saved
	echo "<b>Example 19 </b><br />";
	echo "Get a list of vars saved <br />";
	echo "<ul>var_dump(Data_Registry::init('DEBUG')->listVars())</ul>";
	var_dump(Data_Registry::init("DEBUG")->listVars());
	echo "<br /><br />\n";

// Example 20
// Get a list of vars saved
	echo "<b>Example 20 </b><br />";
	echo "Get a list of all vars saved <br />";
	echo "<ul>var_dump(Data_Registry::init()->listAllVars())</ul>";
	var_dump(Data_Registry::init()->listAllVars());
	echo "<br /><br />\n";
	
And here the manual :

Code: Select all

=============================================================
MANUAL
=============================================================

Install:

	Copy Data_Registry.php to a plugin/library directory as you desire.
	Include file Data_Registry.php in your index.php or in your config file.
	
	Enable sessions in your php.ini file.
	If you use cookies or files, it will work as is.
	Optional: To see examples, copy dr_examples.php and dr_testclass.php in your web base directory 

Change default values (:

	Enable global persistence (by default is disabled):
	
		Data_Registry::setPersistence(TRUE,TRUE);	
		
	Set SESSION varname (by default is 'Data_Registry'):
	
		Data_Registry::setSessionName('SESSIONNAMEVAR');
		// SESSIONAMEVAR - Your desired session name var, as you have in your session handler
		
Set a value:

	Data_Registry::init('NAMESPACE')->set('VAR','VALUE'); 
	// Namespace can be any string;
	// VAR is the varname to store
	// VALUE is the value to store, can be string/integer/array/object
 
Get a value:

	Data_Registry::init('NAMESPACE')->get('VAR'); 
	// Namespace can be any string;
	// VAR is the varname to get from store
	// RETURNS value or FALSE

Set a key to a value:

	Data_Registry::init('NAMESPACE')->setKey('VAR','KEY','VALUE'); 
	// Namespace can be any string;
	// VAR is the varname to store
	// KEY is the varname index to store
	// VALUE is the value to store, can be string/integer/array/object

Get a key from a varname stored:

	Data_Registry::init('NAMESPACE')->getKey('VAR','KEY'); 
	// Namespace can be any string;
	// VAR is the varname to store
	// KEY is the varname index to store
	// RETURNS value or FALSE

Add a key value:

	Data_Registry::init('NAMESPACE')->add('VAR','VALUE'); 
	// Namespace can be any string;
	// VAR is the varname to store
	// VALUE is the value to store, can be string/integer/array/object
	// VALUE is added in a array sequence to VAR
	
Test a value:

	Data_Registry::init('NAMESPACE')->test('VAR'); 
	// Namespace can be any string;
	// VAR is the varname to test
	// RETURN boolean TRUE=exists, FALSE=not exists

Test a key value:

	Data_Registry::init('NAMESPACE')->testKey('VAR','KEY'); 
	// Namespace can be any string;
	// VAR is the varname to test
	// KEY is the key to test
	// RETURN boolean TRUE=exists, FALSE=not exists

Enable global persistence for all namespaces:

	Data_Registry::setPersistence(TRUE,TRUE);
	
Disable global persistence for all namespaces:

	Data_Registry::setPersistence(FALSE,TRUE);
	
Enable persistence for a namespace (when global persistence is disabled):

	Data_Registry::init('NAMESPACE')->setPersistence(TRUE);

Disable persistence for a namespace (when global persistence is disabled):

	Data_Registry::init('NAMESPACE')->setPersistence(TRUE);
	
Get all data from a namespace:

	Data_Registry::init('NAMESPACE')->getNameSpace();
	// RETURNS an array 
	
Get all data from all namespaces:
	
	Data_Registry::getAllNameSpaces();
	// RETURNS an array
	
Clear (unset) a var from namespace:

	Data_Registry::init('NAMESPACE')->clear('VAR');
	// VAR is the varname to clear (unset)
	// RETURNS TRUE (successfull) or FALSE (unsuccessfull)

Clear (unset) a namespace:

	Data_Registry::init('NAMESPACE')->clearNameSpace();
	// VAR is the varname to clear (unset)
	// RETURNS TRUE (successfull) or FALSE (unsuccessfull)

Get a value from var and remove it (similar to flash data):

	Data_Registry::init('NAMESPACE')->getFlash('VAR'); 
	// Namespace can be any string;
	// VAR is the varname to get from store
	// RETURNS value or FALSE

Get a key from a varname stored and remove it:

	Data_Registry::init('NAMESPACE')->getFlashKey('VAR','KEY'); 
	// Namespace can be any string;
	// VAR is the varname to store
	// KEY is the varname index to store
	// RETURNS value or FALSE
	
If global persistence is enabled, all namespaces are loaded automaticly,
but you can get a namespace from SESSION manualy, or override it at any moment:

	Data_Registry::init('NAMESPACE')->restoreNameSpace();
	// Namespace can be any string;

If global persistence is disabled, you can force to save a namespace:

	Data_Registry::init('NAMESPACE')->backupNameSpace();
	// Namespace can be any string;

Delete a SESSION namespace:

	Data_Registry::init('NAMESPACE')->backupNameSpace(FALSE);
	// Namespace can be any string;

Concatenate commands:

	Data_Registry::init('NAMESPACE')->set('VAR','VALUE')->backupNameSpace();
	Data_Registry::init('NAMESPACE')->set('VAR','VALUE')->setPersistence(TRUE)->backupNameSpace();
	Data_Registry::init('NAMESPACE')->set('VAR1','VALUE1')->set('VAR2','VALUE2');
	// Namespace can be any string;

Resusable classes:

	Data_Registry::init('NAMESPACE')->getClass('Classname');
	// Namespace can be any string;
	// Returns the class pointer
	
	Also, can use directlly objects inside a class:
	
	Data_Registry::init('NAMESPACE')->getClass('Classname')->get('field');
	// Namespace can be any string;
	// All classes must to be included before dataStorage call, and if you want persistence with this class, 
	// class file must to be loaded before 'session_start()' command.
	 
List vars stored

	Data_Registry::init('NAMESPACE)->listVars();
	// Namespace can be any string;
	// Returns an array with information about the vars stored on current specified namespace

List all vars stored

	Data_Registry::init()->listAllVars();
	// Returns an array with information about the vars stored on all namespaces	
Download: http://code.google.com/p/data-registry/

For me has been very helpfull, hope would be for you !!

Xavier Perez
Post Reply