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(){
...
}
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,然后实例化它

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.