Review PHP设计模式之——注册模式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Review PHP设计模式之——注册模式相关的知识,希望对你有一定的参考价值。

注册模式:

 1 class DbConnections{
 2     var $_store = array();
 3     public function isValid($key) {
 4         return isset($this->_store[$key]);
 5     }
 6 
 7     public function &get($key){
 8         if (isset($this->_store[$key])) 
 9             return $this->_store[$key];
10     }
11 
12     public function set($key, & $obj) {
13         $this->_store[$key] = & $obj;
14     }
15 
16     public function &getInstance(){
17         static $instance = array();
18         if (!$instance)
19             $instance[0] = & new DbConnections;
20         return $instance[0];
21     }
22 }
23 
24 class mysqlConnection{
25     public $name = false;
26     public function __construct($db){
27         $this->name = $db;
28         echo $db, "\n";
29     }
30 
31     public function append($str){
32         $this->name .= " ".$str;
33     }
34 }
35 
36 //initial setup, somewhere near the start of your script
37 $dbc = & DbConnections::getInstance();
38 $dbc->set(‘server1‘, new MysqlConnection(‘db1‘));
39 $dbc->set(‘server2‘, new MysqlConnection(‘db2‘));
40 $dbc->set(‘server3‘, new MysqlConnection(‘db3‘));
41 
42 
43 $dbc1 = $dbc->get(‘server1‘);
44 $dbc2 = $dbc->get(‘server2‘);
45 $dbc3 = $dbc->get(‘server3‘);
46 
47 $dbc1->append("connection");
48 
49 var_dump($dbc->get(‘server1‘));
50 var_dump($dbc->get(‘server2‘));
51 var_dump($dbc->get(‘server3‘));

 

以上是关于Review PHP设计模式之——注册模式的主要内容,如果未能解决你的问题,请参考以下文章

php模式设计之 注册树模式

php设计模式之注册模式

PHP设计模式之工厂/单例/注册者模式

PHP模式设计之单例模式工厂模式注册树模式适配器模式观察者模式

PHP面向对象之注册表模式

crucible VS gerrit