我們學(xué)習(xí)了解了這么多關(guān)于PHP的知識(shí),今天學(xué)習(xí)如何一招解決 PHP 單例模式解析和實(shí)戰(zhàn),不知你們是否已經(jīng)完全掌握了呢,如果沒(méi)有,那就跟隨本篇文章一起繼續(xù)學(xué)習(xí)吧 一、什么是單例模式? 1、含義 作為對(duì)象的創(chuàng)建模式,單例模式確保某一個(gè)類只有一個(gè)實(shí)例,而且自行實(shí)例化并向整個(gè)系統(tǒng)全局地提供這個(gè)實(shí)例。它不會(huì)創(chuàng)建實(shí)例副本,而是會(huì)向單例類內(nèi)部存儲(chǔ)的實(shí)例返回一個(gè)引用。 2、單例模式的三個(gè)要點(diǎn): (1). 需要一個(gè)保存類的唯一實(shí)例的靜態(tài)成員變量: (2). 構(gòu)造函數(shù)和克隆函數(shù)必須聲明為私有的,防止外部程序new類從而失去單例模式的意義: (3). 必須提供一個(gè)訪問(wèn)這個(gè)實(shí)例的公共的靜態(tài)方法(通常為getInstance方法),從而返回唯一實(shí)例的一個(gè)引用 二、為什么要使用單例模式? 1、PHP缺點(diǎn): PHP語(yǔ)言是一種解釋型的腳本語(yǔ)言,這種運(yùn)行機(jī)制使得每個(gè)PHP頁(yè)面被解釋執(zhí)行后,所有的相關(guān)資源都會(huì)被回收。也就是說(shuō),PHP在語(yǔ)言級(jí)別上沒(méi)有辦法讓某個(gè)對(duì)象常駐內(nèi)存,這和asp.net、Java等編譯型是不同的,比如在Java中單例會(huì)一直存在于整個(gè)應(yīng)用程序的生命周期里,變量是跨頁(yè)面級(jí)的,真正可以做到這個(gè)實(shí)例在應(yīng)用程序生命周期中的唯一性。然而在PHP中,所有的變量無(wú)論是全局變量還是類的靜態(tài)成員,都是頁(yè)面級(jí)的,每次頁(yè)面被執(zhí)行時(shí),都會(huì)重新建立新的對(duì)象,都會(huì)在頁(yè)面執(zhí)行完畢后被清空,這樣似乎PHP單例模式就沒(méi)有什么意義了,所以PHP單例模式我覺(jué)得只是針對(duì)單次頁(yè)面級(jí)請(qǐng)求時(shí)出現(xiàn)多個(gè)應(yīng)用場(chǎng)景并需要共享同一對(duì)象資源時(shí)是非常有意義的。 2、單例模式在PHP中的應(yīng)用場(chǎng)合: (1)、應(yīng)用程序與數(shù)據(jù)庫(kù)交互 一個(gè)應(yīng)用中會(huì)存在大量的數(shù)據(jù)庫(kù)操作,比如過(guò)數(shù)據(jù)庫(kù)句柄來(lái)連接數(shù)據(jù)庫(kù)這一行為,使用單例模式可以避免大量的new操作,因?yàn)槊恳淮蝞ew操作都會(huì)消耗內(nèi)存資源和系統(tǒng)資源。 (2)、控制配置信息 如果系統(tǒng)中需要有一個(gè)類來(lái)全局控制某些配置信息, 那么使用單例模式可以很方便的實(shí)現(xiàn). 三、如何實(shí)現(xiàn)單例模式? 1、普通的數(shù)據(jù)庫(kù)訪問(wèn)例子: 2、應(yīng)用單例模式對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作: 3、深入理解 推薦學(xué)習(xí):《PHP視頻教程》
private static $_instance;
private function __construct() { $this->_db = pg_connect('xxxx'); } private function __clone() { }//覆蓋__clone()方法,禁止克隆
public static function getInstance() { if(! (self::$_instance instanceof self) ) { self::$_instance = new self(); } return self::$_instance; }
<?php ...... //初始化一個(gè)數(shù)據(jù)庫(kù)句柄 $db = new DB(...); //添加用戶信息 $db->addUserInfo(...); ...... //在函數(shù)中訪問(wèn)數(shù)據(jù)庫(kù),查找用戶信息 function getUserInfo() { $db = new DB(...);//再次new 數(shù)據(jù)庫(kù)類,和數(shù)據(jù)庫(kù)建立連接 $db = query(....);//根據(jù)查詢語(yǔ)句訪問(wèn)數(shù)據(jù)庫(kù) } ?>
<?php class DB { private $_db; private static $_instance; private function __construct(...) { $this->_db = pg_connect(...);//postgrsql } private function __clone() {}; //覆蓋__clone()方法,禁止克隆 public static function getInstance() { if(! (self::$_instance instanceof self) ) { self::$_instance = new self(); } return self::$_instance; } public function addUserInfo(...) { } public function getUserInfo(...) { } } //test $db = DB::getInstance(); $db->addUserInfo(...); $db->getUserInfo(...); ?>
<?php class db { public $conn; public static $sql; public static $instance=null; private function __construct(){ require_once('db.config.php'); $this->conn = mysql_connect($db['host'],$db['user'],$db['password']); if(!mysql_select_db($db['database'],$this->conn)){ echo "失敗"; }; mysql_query('set names utf8',$this->conn); } public static function getInstance(){ if(is_null(self::$instance)){ self::$instance = new db; } return self::$instance; } /** * 查詢數(shù)據(jù)庫(kù) */ public function select($table,$condition=array(),$field = array()){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } $fieldstr = ''; if(!empty($field)){ foreach($field as $k=>$v){ $fieldstr.= $v.','; } $fieldstr = rtrim($fieldstr,','); }else{ $fieldstr = '*'; } self::$sql = "select {$fieldstr} from {$table} {$where}"; $result=mysql_query(self::$sql,$this->conn); $resuleRow = array(); $i = 0; while($row=mysql_fetch_assoc($result)){ foreach($row as $k=>$v){ $resuleRow[$i][$k] = $v; } $i++; } return $resuleRow; } /** * 添加一條記錄 */ public function insert($table,$data){ $values = ''; $datas = ''; foreach($data as $k=>$v){ $values.=$k.','; $datas.="'$v'".','; } $values = rtrim($values,','); $datas = rtrim($datas,','); self::$sql = "INSERT INTO {$table} ({$values}) VALUES ({$datas})"; if(mysql_query(self::$sql)){ return mysql_insert_id(); }else{ return false; }; } /** * 修改一條記錄 */ public function update($table,$data,$condition=array()){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } $updatastr = ''; if(!empty($data)){ foreach($data as $k=>$v){ $updatastr.= $k."='".$v."',"; } $updatastr = 'set '.rtrim($updatastr,','); } self::$sql = "update {$table} {$updatastr} {$where}"; return mysql_query(self::$sql); } /** * 刪除記錄 */ public function delete($table,$condition){ $where=''; if(!empty($condition)){ foreach($condition as $k=>$v){ $where.=$k."='".$v."' and "; } $where='where '.$where .'1=1'; } self::$sql = "delete from {$table} {$where}"; return mysql_query(self::$sql); } public static function getLastSql(){ echo self::$sql; } } $db = db::getInstance(); //$list = $db->select('demo',array('name'=>'tom','password'=>'ds'),array('name','password')); //echo $db->insert('demo',array('name'=>'最近你啦','password'=>'123')); //echo $db->update('demo',array("name"=>'xxx',"password"=>'123'),array('id'=>1)); echo $db->delete('demo',array('id'=>'2')); db::getLastSql(); echo "<pre>"; ?>