Instructions for the use of Zend's Registry mechanism

  • 2020-06-01 09:14:57
  • OfStack

There are many global variables in the project process, which need to be stored globally. Is it possible to use global variables for storage? That would be too weak. Zend USES the Registry mechanism (registry) to store objects and values, and is a container for storing objects and values.

The Zend_Registry class does just that

Code sample
Zend_Registry::set('config', $config);
Zend_Registry::get('config');

The code analysis
These are the two functions that are most commonly used. Let's look at 1 for this class

class Zend_Registry extends ArrayObject

This class inherits from ArrayObject

ArrayObject implements IteratorAggregate , Traversable , ArrayAccess , Serializable , Countable

ArrayObject is a collection of objects, equivalent to the concept of a generic collection in other languages.

void ArrayObject::offsetSet (mixed $index, mixed $newval), this function is key, value, just key, value can be any type.

Ok, so back to Zend_Registry, what does set do

set function


public static function set($index, $value) 
    { 
        $instance = self::getInstance(); 
        $instance->offsetSet($index, $value); 

    } 

One is to instantiate Register, and the other is to call the offsetSet method and set index and value.

The offset method is easy to understand, but why use the getInstance method?

This is a singleton pattern that combines static methods of a class.

Our one-like singleton pattern is written as follows:


class A{ 
    private $_instance; 
    public static function getInstance(){ 
        ... 
    } 

    protected function __construct(){ 
        ... 
    } 

    public function setVal(){ 
        ... 
    } 
} 

$a = A::getInstance(); 

$a->setVal();

So you need to instantiate a class before you call it, which is actually a singleton, but it's uncomfortable

register over here does this directly using static method calls

A::setVal();

So the general idea of the code is I wrote demo


class A{ 
    private static $_instance; 
    public static function getInstance(){ 
        if(self::_instance !==null){ 
            return $this->_instance; 
        } else { 
            return new A(); 
        } 
    } 

    public function __construct(){ 

    } 

    public static function setV(){ 
        $a = self::getInstance(); 
        $a->setVal(); 
    } 

    public function setVal(){ 
        ... 
    } 
} 

A::setV();

S actually just open up the s 80en () to s 81en and then instantiate it


Related articles: