Every php developer wants to write a php framework. But before the start write a framework we should know some php automation rules. You can ask me like this question Why we need to object registry? Because the most popular frameworks use a base registry class for storing objects. Code Igniter use PHP4 object register methods but i don’t know anything about Cake php .
I said something about singleton pattern preceding article http://develturk.com/2009/04/17/prevent-duplication-of-memory-with-php5-singleton-design-pattern/
You learned from above the article how to declare a class as a static and you learned how to use it in multiple class operations.
We don’t want add Singleton Pattern to every classes so , we should write one class for this job ..
/*
* A Registry Example for Automatically
* getInstance() operations.
* Ersin Güvenç.
*/
/* Our interface */
abstract class Registry
{
abstract protected function get($key);
//get stored object.
abstract protected function set($key,$val);
//set object.(store object)
}
Class My_Registry extends Registry {
/**
* Registry array of objects
* @access private
*/
private static $objects = array();
/**
* The instance of the registry
* @access private
*/
private static $instance;
//prevent directly access.
private function __construct(){}
//prevent clone.
public function __clone(){}
/**
* singleton method used to access the object
* @access public
*/
public static function singleton()
{
if(!isset(self::$instance))
{
self::$instance = new self();
echo "new instance\n";
} else {
echo "old instance\n";
}
return self::$instance;
}
/*
* get object protected function you can use only
* inside from this class.
*/
protected function get($key)
{
if(isset($this->objects[$key]))
{
return $this->objects[$key];
}
return NULL;
}
/*
* set object protected function you can use only
* inside from this class.
*/
protected function set($key,$val)
{
$this->objects[$key] = $val;
}
/*
* get stored object
*/
static function getObject($key)
{
return self::singleton()->get($key);
}
/*
* store object
*/
static function storeObject($key, $instance)
{
return self::singleton()->set($key,$instance);
}
} //end of the class.
/*
* Our cavy class..
*/
Class A
{
public $numberOne;
public $numberTwo;
function __construct()
{
$this->numberOne = "5";
$this->numberTwo = "5";
}
function sum()
{
$total = $this->numberOne + $this->numberTwo;
return $total;
}
} //end class A.
$Registry = My_Registry::singleton();
//OUTPUT new instance
$Registry->storeObject('A', new A());
//OUTPUT old instance
/*
* I can declare class A everywhere in my
* framework one or more times.
*/
$a = $Registry->getObject('A');
//OUTPUT old instance
$b = $Registry->getObject('A');
//OUTPUT old instance
$c = $Registry->getObject('A');
//OUTPUT old instance
$d = $Registry->getObject('A');
//OUTPUT old instance
//TOTAL OUTPUT:
// new instance
// old instance
// old instance
// old instance
// old instance
// old instance
Awesome, love this