views:

212

answers:

4

Hey I'm wondering when accessing Zend_Registry in an application if you need to include getInstance() and if so, why?

for example

    Zend_Registry::getInstance()->get('db');

vs.

    Zend_Registry::get('db');

they both seem to work with the later being less verbose. I vaguely understand that Zend_Registry is a singleton, which I think means there can only be one instance of it? so why would you need getInstance()?

A: 

No, you don't need to use getInstance(). It's there, I believe, for other areas of the API. It's also a common pattern when creating singletons to expose a getInstance() method to use to get the instance of that singleton. So, it's defined to adhere to that pattern.

awgy
+1  A: 

You have not to use getInstance(). If you will look inside Zend_Registry class you will see:

  public static function get($index)
    {
        $instance = self::getInstance();

        if (!$instance->offsetExists($index)) {
            require_once 'Zend/Exception.php';
            throw new Zend_Exception("No entry is registered for key '$index'");
        }

        return $instance->offsetGet($index);
    }

It is getting instance for you in static methods.

hsz
Thanks for pointing that out
RueTheWhirled
A: 

You might want to use Zend_Registry::getInstance() if you are looking to access a number of calls to the registry; instead of going through calls to the offsetExists() method and subsequent calls to array_key_exists() for each property, you get an instance and then go via the ArrayObject methods to get stored entries.

Another reason that you might want to use Zend_Registry::getInstance() is if you are storing the registry in a cache.

Other than that, you may find Zend_Registry::get() is all that you need.

Cez
+3  A: 

I wrote the code for Zend_Registry in 2007.

You can use the static get() and set(), and it affects the default instance of the registry, stored as a static member of the class. This is the intended usage for most situations.

All the other methods of Zend_Registry are pretty much to support non-typical situations, like if you wanted to implement your own class for your registry but still make it the default singleton. Or if you want to get the actual registry object, for example so you can serialize the whole registry object with all its contents.

Bill Karwin