try { go_fish(); } catch(JDOMException){} | Home | Twitter API Client Released

Filed under Quick Tips on June 2, 2008 by Dave Hauenstein

A More Convenient Zend_Registry

The Zend_Registry is a pretty useful part of the MVC architecture of the Zend Framework. It’s a singleton class that keeps the developer from having to define global variables throughout their application. The downside is that retrieving the variables stored in the Zend_Registry can be tedious and annoying if you’re doing it often. Here’s an example:

$config = Zend_Registry::get('config');

Pretty verbose, huh? From that point on you can access the variables inside of config:

If($config->settings->environment == ‘development’) …

Wouldn’t it be much simpler if, whenever you needed to retrieve something from the Zend_Registry inside of your controllers, you could access them inline? For example:

$this->registry->config->settings->environment

In order to get this to work, you need to extend the Zend_Controller_Action class and overload the __get method. Here’s the code:

class Zarc_Controller_Action extends Zend_Controller_Action

{
   /**
    * overload __get in order to easily retrieve values from the Registry
    * and other sources. Throw an exception if the param could not be found.
    */
   public function __get($param)
   {
       if($param == 'registry' || $param == 'r')
       {
           return new Zarc_Registry();
       }
       else
       {
           throw new Exception("Could not find property {$param}");
       }
   }
}

All of your controller classes should now extend the new controller class you just created. For example:

Class IndexController extends Zarc_Controller_Action

Next, you need to write a class that searches the Zend_Registry for the property that is being requested.

/**
 * Applies an interface to the Zend_Registry that is cleaner and more
 * accessible than doing it the verbose Zend Framework way.
 */
class Zarc_Registry
{
   public function __get($param)
   {
       if(Zend_Registry::isRegistered($param))
       {
           return Zend_Registry::get($param);
       }
       else
       {
           throw new Zarc_Exception("Could not find property {$param}");
       }
   }
}

Then, save the two classes you created to your include path. Now, from your controller action methods you can access any variable stored in the Zend_Registry like this:

$this->registry->param
and this:
$this->r->param

This saves some time and makes your code much cleaner. You can also do this with sessions. Try it out, or ask us questions! If you need a deeper understanding leave us some comments and we’ll help you out.

Post a Comment Digg Del.icio.us

Trackback Pings (TrackBack URL for this entry)

http://www.arc90.com/cgi-bin/mt4/mt-tb.cgi/149.

Post a Comment:

try { go_fish(); } catch(JDOMException){} | Main | Twitter API Client Released