Monday, December 21, 2009

Using the registry

In this example, we store values in the registry, and we retrieve values from the registry. We access the registry with the static methods, or we access the registry as an array or as an object.

Components used in this example
Implementation of a registry

class MyRegistry
Processing the registry
  • We get the method and the action,
  • We load the content of the registry. The content of registry is made persistent for the purpose of this example.
  • We get the value to store in the registry.
  • We store the value in the registry with the requested method.
  • We save the content of the registry.
  • If we catch an exception, we return the error message.

    public function process()
// We get the method and the action,
list($method$action) = $this->_getParameters();

        try {
$result = array();

// We load the content of the registry.
            // The content of registry is made persistent for the purpose of this example.
$data $this->_loadRegistry();
// We get the value to store in the registry.
@list($key$value) = explode(' => '$action);
$value or $value null;

// We store the value in the registry with the requested method.
switch ($method) {
array_key_exists('fruit'$data) and
array_key_exists('color'$data) and
array_key_exists('count'$data) and
$key and Zend_Registry::set($key$value);

$registry = new Zend_Registry($data);
$key and $registry[$key] = $value;

$registry = new Zend_Registry($dataArrayObject::ARRAY_AS_PROPS);
$key and $registry->$key $value;

// We save the content of the registry.

$result Zend_Registry::getInstance();

        } catch (
Exception $e) {
// If we catch an exception, we return the error message.
$result $e->getMessage();

        return array(
Extraction of the parameters from the GET request

    private function _getParameters()
$method = isset($_GET['method'])? $_GET['method'] : null;
$action = isset($_GET['action'])? $_GET['action'] : null;

        return array(
Loading the registry from the cookie

    private function _loadRegistry()
$_COOKIE['registry']) and
$registry unserialize(stripcslashes($_COOKIE['registry'])) and
is_array($registry) or
$registry = array();

Saving the registry in a cookie

    private function _SaveRegistry()
$registry = array();
Zend_Registry::isRegistered('fruit') and $registry['fruit'] = Zend_Registry::get('fruit');
Zend_Registry::isRegistered('color') and $registry['color'] = Zend_Registry::get('color');
Zend_Registry::isRegistered('count') and $registry['count'] = Zend_Registry::get('count');
setcookie('registry'serialize($registry), time() + 3600'/');


No comments:

Post a Comment