PHP 教程
—
Zend 的 Registry 机制的使用说明
本文主要为大家说明
Zend 的 Registry 机制的使用。供参考下
项目过程中有很多全局变量,
需要全局存储,是否是使用全局变量来进行存储?那就弱爆
了。
Zend 使用 Registry 机制(注册表)存储对象和值,是一个存储对象和值的容器。
Zend_Registry 这个类就是做这个目的
代码示例
Zend_Registry::set('config',
$config
);
Zend_Registry::get('config');
代码分析
这两个函数是最常用的两个函数。我们来看一下这个类
class
Zend_Registry
extends
ArrayObject
这个类继承自
ArrayObject
ArrayObject
implements
IteratorAggregate , Traversable , ArrayAccess , Serializable , Countable
ArrayObject 是一个对象集合,相当于其他语言的泛型集合的概念。
重点了解下
void ArrayObject::offsetSet ( mixed
$index
, mixed
$newval
), 这个函数就是
hashtable 中的设置 key,value,只是 key,value 可以是任何类型的。
好了,回到
Zend_Registry, 看看 set 做了些什么事情
set 函数
代码如下
:
public
static
function
set(
$index
,
$value
)
{
$instance
= self::getInstance();
$instance
->offsetSet(
$index
,
$value
);
}
一个是实例化
Register,另一个是调用 offsetSet 方法,将 index 和 value 设置进去。
offset 方法很好理解,但是为什么要使用 getInstance 方法呢?
这里建议大家好好看看,这个是结合类静态方法的单例模式。
我们一般的单例模式写成:
代码如下
:
class
A{
private
$_instance
;
public
static
function
getInstance(){
...