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.
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.
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.
require_once('Zend/Registry.php'); try { $name = Zend_Registry::get('name'); } catch (Exception $ex) { // entry with key 'name' does not exist }
Once you've retrieved the value from the registry you can then proceed to use it as normal.




