码迷,mamicode.com
首页 > Web开发 > 详细

php设计模式入门-注册表模式

时间:2015-07-29 23:07:05      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:php设计模式   注册表模式   

对于这个模式的应用场景不是太好总结,只是根据之前的经验,注册表类里面经常会存储一些别的地方需要用到的对象,比如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'));


版权声明:本文为博主原创文章,未经博主允许不得转载。

php设计模式入门-注册表模式

标签:php设计模式   注册表模式   

原文地址:http://blog.csdn.net/u011250882/article/details/47134705

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!