Heim  >  Artikel  >  Backend-Entwicklung  >  php设计模式入门-注册表模式_PHP教程

php设计模式入门-注册表模式_PHP教程

WBOY
WBOYOriginal
2016-07-13 09:45:28748Durchsuche

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(&#39;key1&#39;, &#39;hello&#39;);<span style="white-space:pre">	</span>//只是为了测试,通常注册表中存储的数据都是对象
var_dump($registry->get(&#39;key1&#39;));
var_dump($registry->get(&#39;key2&#39;));

 

 

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1040918.htmlTechArticlephp设计模式入门-注册表模式 对于这个模式的应用场景不是太好总结,只是根据之前的经验,注册表类里面经常会存储一些别的地方需要用...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn