对于这个模式的应用场景不是太好总结,只是根据之前的经验,注册表类里面经常会存储一些别的地方需要用到的对象,比如redis、memcache类,还比如配置信息config类等,它扮演的是一个类似于全局变量的角色。具体的实现其实非常简单,如下代码所示:
<?php
class Registry{
static $instance;
public $containers = array();
static function getInstance(){
if(is_null(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
public function set($key, $value){
$this->containers[$key] = $value;
}
public function get($key){
return isset($this->containers[$key]) ? $this->containers[$key] : null;
}
}
$registry = Registry::getInstance();
$registry->set('key1', 'hello');<span style="white-space:pre"> </span>//只是为了测试,通常注册表中存储的数据都是对象
var_dump($registry->get('key1'));
var_dump($registry->get('key2'));
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u011250882/article/details/47134705