Monday, March 16, 2009

Zend framework source code learning - Zend_Registry

Zend_Registry extends ArrayObject, which is a class in Standard PHP Library(SPL).
Let's take a look at its set method:
public static function set($index, $value)
$instance = self::getInstance();
$instance->offsetSet($index, $value);
We can see, although it is a static method, it implements a singleton inside: $instance = self::getInstance().

offsetSet($index, $value) is a method of ArrayObject. It will set the value at the specified $index as $value.

Now let's check through get method:
public static function get($index)
$instance = self::getInstance();

if (!$instance->offsetExists($index)) {
require_once 'Zend/Exception.php';
throw new Zend_Exception("No entry is registered for key '$index'");

return $instance->offsetGet($index);
It gets a singleton instance and tries to call offsetGet($index), which is another ArrayObject method to return the value at $index. If the specified $index doesn't exist, it throws an exception.

We use Zend_Registry to store the resources that must be accessed through the whole web site, such as database resource.

No comments: