PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Zend Framework 101: Zend_Registry

Accessing the Registry

There are three key functions in accessing the registry: writing a variable, reading a variable, and checking if a value exists in the registry.

Writing to the Registry

To write to the registry, use the Zend_Registry::set() static method. This method accepts two arguments: the name of the item as it will be referred to in the registry, and the value to store in the registry. Listing 1 shows an example of this.

Listing 1 Writing to the registry (listing-1.php)
<?php
    require_once('Zend/Registry.php');
 
    $name = 'Quentin Zervaas';
    Zend_Registry::set('name', $name);
?>

You can write complex objects (that is, any variable), not just simple variables like strings or integers.

Checking if A Value Exists

To check if a particular value exists in the registry, use the Zend_Registry::isRegistered() static method. This method accepts the name of the variable to check for as its only argument. If the variable exists true is returned, otherwise false is returned. Listing 2 shows an example of this.

Listing 2 Checking if a registry value exists (listing-2.php)
<?php
    require_once('Zend/Registry.php');
 
    if (Zend_Registry::isRegistered('name')) {
        // value is in registry
    }
    else {
        // value is not in registry
    }
?>

Retrieving Registry Values

To retrieve a value from the registry, use the Zend_Registry::get() method. This method accepts the name of variable to retrieve. If the value doesn't exist then the Zend_Exception exception is thrown. Handling the exception is a good alternative to using isRegistered() to check for a value existing in the registry.

Listing 3 shows an example of retrieving a value from the registry and handling the case where the value doesn't exist.

Listing 3 Retrieving a variable from the registry (listing-3.php)
<?php
    require_once('Zend/Registry.php');
 
    try {
        $name = Zend_Registry::get('name');
    }
    catch (Exception $ex) {
        // entry with key 'name' does not exist
    }
?>
Tip: Typically when you're accessing a registry variable you will know that it exists so you can skip handling the exception.

Once you've retrieved the value from the registry you can then proceed to use it as normal.

In This Article