代码改变世界

Zend的Registry机制

2012-08-03 10:02  轩脉刃  阅读(2877)  评论(0编辑  收藏  举报

项目过程中有很多全局变量, 需要全局存储,是否是使用全局变量来进行存储?那就弱爆了。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(){
        ...
    }
    
    protected function __construct(){
        ...
    }
    
    public function setVal(){
        ...
    }
}

$a = A::getInstance();

$a->setVal();

 

这样在调用之前就需要实例化一个类,虽然这个实例化实际上是单例,但感觉还是不舒服

这边的register就做到了直接使用静态方法调用

A::setVal();

大致的代码思路我写了个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();

实际上就是直接把__construct()放开成为public,然后实例化它

为什么要使用Registry

推荐看这一篇帖子:http://stackoverflow.com/questions/2531168/zend-registry-real-life-examples