Description of Zend Registry mechanism. There are many global variables in the project process and they need to be stored globally. is it stored using global variables? Then it is weak. Zend uses the Registry mechanism (Registry) to store objects and values. There are many global variables in the project process and global storage is required. is it using global variables for storage? Then it is weak. Zend uses the Registry mechanism (Registry) to store objects and values. it is a container that stores objects and values.
Zend_Registry is used for this purpose.
Sample code
Zend_Registry: set ('config', $ config );
Zend_Registry: get ('config ');
Code analysis
These two functions are the two most commonly used functions. Let's take a look at this class.
Class Zend_Registry extends ArrayObject
This class is inherited from ArrayObject
ArrayObject implements IteratorAggregate, Traversable, ArrayAccess, Serializable, Countable
ArrayObject is an object set, which is equivalent to the generic set concept in other languages.
Focus on void ArrayObject: offsetSet (mixed $ index, mixed $ newval). This function is used to set the key and value in hashtable, but only the key and value can be of any type.
Okay. go back to Zend_Registry and check what set has done.
Set function
The code is as follows:
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 the index and value.
The offset method is easy to understand, but why should we use the getInstance method?
We recommend that you take a good look. this is a singleton mode combining static methods.
The common singleton mode is as follows:
The code is as follows:
Class {
Private $ _ instance;
Public static function getInstance (){
...
}
Protected function _ construct (){
...
}
Public function setVal (){
...
}
}
$ A = A: getInstance ();
$ A-> setVal ();
In this way, a class needs to be instantiated before calling. Although this instantiation is actually a singleton, it still feels uncomfortable.
Here, the register can be called directly using static methods.
A: setVal ();
I wrote a demo about the general code.
The code is as follows:
Class {
Private static $ _ instance;
Public static function getInstance (){
If (self: _ instance! = Null ){
Return $ this-> _ instance;
} Else {
Return new ();
}
}
Public function _ construct (){
}
Public static function setV (){
$ A = self: getInstance ();
$ A-> setVal ();
}
Public function setVal (){
...
}
}
A: setV ();
In fact, we just open _ construct () to public and instantiate it.
Global storage is required. is global variables used for storage? Then it is weak. Zend uses the Registry mechanism (Registry) to store objects and values ,...