Using the Zend_Registry in PHP

Posted in PHP -

The Zend Framework has a component called the Zend_Registry which allows you to store data into a sort of global space which lasts the duration of the script. Once saved to the registry the data is available throughout the application. This post shows how to save some data to the registry and then retrieve it.

You don't need to create a Zend_Registry object and can simply access it via its static methods.

Saving and retrieving a value

To save a value to the registry use the set() method as follows:

$value = 'xyz';
Zend_Registry::set('foo', $value);

To retrieve a value from the registry use the get() method as follows, which then echoes the output (using the value from the above example 'xyz' would be echo'd out):

$x = Zend_Registry::get('foo');
echo $x;

Note that subsequently changing the value of $x in the second example will not change the value stored in the registry; you would need to save it back to the registry using set() again. Therefore, the following example would still echo out 'xyz':

$x = 123;
echo Zend_Registry::get('foo');

Saving and retrieving an array

This is the same as for saving a regular value above. A copy of the array is made to the registry and subsequent modifications to the variable do not affect the registry unless saved back to it again. Object handling is different and is covered in the next section.

Therefore:

$value = array(1, 2, 3);
Zend_Registry::set('foo', $value);
$value[] = 4;
$x = Zend_Registry::get('foo');
print_r($x);

would output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

i.e. the new element '4' in $value has not been added to the array in the registry.

Saving and retreiving an object

When saving an object to the registry, it is a reference to the object that is saved. Subsequent changes to the original object therefore affect the copy in the registry.

For example if we had the following class:

class foo {

    var $a;
    var $b;
    var $c;
   
}

And did the following:

$value = new foo();
Zend_Registry::set('foo', $value);
$value->a = 1;
$value->b = 2;
$value->c = 3;
print_r(Zend_Registry::get('foo'));

The output would be:

foo Object
(
    [a] => 1
    [b] => 2
    [c] => 3
)

This is despite the assignments to ->a ->b and ->c being after the object has been saved to the registry.

Adding objects such as a session object to the registry can be a really useful way of passing information around, because all you need to do is get the object from the registry and then call functions and assign variables and they will be accessible from anywhere else in your code that gets the object from the registry.



Related posts:


Comments