有段时间没更新博客了,最近一段时间在捣鼓框架,几个框架倒来倒去的。主要的还是研究了zend framework。现介绍下zend framework的注册模式。
很多时候,有经验的php程序员都告诫我们,慎用全局变量,全局变量不好管理呀。稍不注意就会致使全局变量滥用。Zend framework 提供了一个注册模式来对全局变量进行管理。它的实质是类似对一个数组进行操作。首先注册变量,把全局变量set进数组,取的时候get 全局变量。其中它继承了spl 的ArrayObject类来进行操作。注册模式一般会跟单例模式一起用。为了保证注册唯一呀。下面贴上zend framework的Register代码。
<?php
classZend_Registry extends ArrayObject
{
private static $_registryClassName ='Zend_Registry';
private static $_registry = null;
//得到单例
public static function getInstance()
{
if (self::$_registry === null) {
self::init();
}
return self::$_registry;
}
//设置单例
public static functionsetInstance(Zend_Registry $registry)
{
if (self::$_registry !== null) {
require_once 'Zend/Exception.php';
throw new Zend_Exception('Registryis already initialized');
}
self::setClassName(get_class($registry));
self::$_registry = $registry;
}ArrayObject
//初始化
protected static function init()
{
self::setInstance(newself::$_registryClassName());
}
public static functionsetClassName($registryClassName = 'Zend_Registry')
{
if (self::$_registry !== null) {
require_once 'Zend/Exception.php';
throw new Zend_Exception('Registryis already initialized');
}
if (!is_string($registryClassName)) {
require_once 'Zend/Exception.php';
throw newZend_Exception("Argument is not a class name");
}
/**
* @see Zend_Loader
*/
require_once 'Zend/Loader.php';
Zend_Loader::loadClass($registryClassName);
self::$_registryClassName =$registryClassName;
}
//注销单例
public static function _unsetInstance()
{
self::$_registry = null;
}
//得到已注册的数据
public static function get($index)
{
$instance = self::getInstance();
if(!$instance->offsetExists($index)) {
require_once 'Zend/Exception.php';
throw new Zend_Exception("Noentry is registered for key '$index'");
}
return $instance->offsetGet($index);
}
//设置值,索引与值对应
public static function set($index, $value)
{
$instance = self::getInstance();
$instance->offsetSet($index, $value);
}
//判断是否已注册
public static function isRegistered($index)
{
if (self::$_registry === null) {
return false;
}
returnself::$_registry->offsetExists($index);
}
public function __construct($array =array(), $flags = parent::ARRAY_AS_PROPS)
{
parent::__construct($array, $flags);
}
//判断是否已存在
public function offsetExists($index)
{
return array_key_exists($index, $this);
}
}