ZPF MYSQL資料庫層多執行個體實現

來源:互聯網
上載者:User

標籤:

2015年3月31日 18:27:34

情景: 一次請求, 可能要連結多個不同的資料庫, 比如說主從, 為了避免重複connect資料庫, 可以將已經連結的資料庫物件儲存下來

下一次調用的時候, 直接取出來使用就行了

實現: 

 1 class mysqldb 2 { 3     //多主機執行個體 4     private static $instance = array(); 5     //串連 6     public $link = null; 7      8     public $_database = ‘‘;//當前資料庫名 9     public $_tablename = ‘‘;//當前表的表名10     public $_dt =‘‘;//database.tablename11     12     13     //如果主機沒變,並且已經存在MYSQL串連,就不再建立新的串連14     //如果主機改變,就再產生一個執行個體建立一個串連15     public static function getInstance($host, $username, $password, $database, $tablename)16     {17         if (empty(self::$instance[$host])) {18             $rc = new ReflectionClass(‘mysqldb‘);19             self::$instance[$host] = $rc->newInstanceArgs(array($host, $username, $password, $database, $tablename));20         }21 22         return self::$instance[$host];23     }24     25     public function __construct($host, $username, $password, $database, $tablename)26     {27         $this->link = new mysqli($host, $username, $password);28         if($this->link->connect_error) {29             echo $this->link->connect_error,‘<br>‘;30             exit;31         }32         $this->_database = $database;//database name33         $this->_tablename = $tablename;//table name34         $this->_dt = "`{$this->_database}`.`{$this->_tablename}`";35 36         $this->link->query("set names utf8");37     }38 }

注意: 使用反射功能實現, 建構函式為public

使用方法:

1     public function testmysqls()2     {3         $obj1 = $this->getlink(‘tiezi‘);4         $obj2 = $this->getlink(‘name‘);5 6         $arr1 = $obj1->select(‘‘, ‘‘, ‘‘, 1);7         $arr2 = $obj2->select(‘‘, ‘‘, ‘‘, 1);8         var_dump($arr1, $arr2);9     }

 

ZPF MYSQL資料庫層多執行個體實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.