PHP基于单例模式编写PDO类的方法
一、单例模式简介
简单的说,一个对象(在学习设计模式之前,需要比较了解面向对象思想)只负责一个特定的任务;
二、为什么要使用PHP单例模式?
1、php的应用主要在于数据库应用,所以一个应用中会存在大量的数据库操作,使用单例模式,则可以避免大量的new操作消耗的资源。
2、如果系统中需要有一个类来全局控制某些配置信息,那么使用单例模式可以很方便的实现.这个可以参看ZF的FrontController部分。
3、在一次页面请求中,便于进行调试,因为所有的代码(例如数据库操作类db)都集中在一个类中,我们可以在类中设置钩子,输出日志,从而避免到处var_dump,echo。
三、PHP基于单例模式编写PDO类的示例代码
代码如下:
<?php /** *MyPDO *@authorJason.Wei<jasonwei06@hotmail.com> *@licensehttp://www.sunbloger.com/ *@version5.0utf8 */ classMyPDO { protectedstatic$_instance=null; protected$dbName=''; protected$dsn; protected$dbh; /** *构造 * *@returnMyPDO */ privatefunction__construct($dbHost,$dbUser,$dbPasswd,$dbName,$dbCharset) { try{ $this->dsn='mysql:host='.$dbHost.';dbname='.$dbName; $this->dbh=newPDO($this->dsn,$dbUser,$dbPasswd); $this->dbh->exec('SETcharacter_set_connection='.$dbCharset.',character_set_results='.$dbCharset.',character_set_client=binary'); }catch(PDOException$e){ $this->outputError($e->getMessage()); } } /** *防止克隆 * */ privatefunction__clone(){} /** *Singletoninstance * *@returnObject */ publicstaticfunctiongetInstance($dbHost,$dbUser,$dbPasswd,$dbName,$dbCharset) { if(self::$_instance===null){ self::$_instance=newself($dbHost,$dbUser,$dbPasswd,$dbName,$dbCharset); } returnself::$_instance; } /** *Query查询 * *@paramString$strSqlSQL语句 *@paramString$queryMode查询方式(AllorRow) *@paramBoolean$debug *@returnArray */ publicfunctionquery($strSql,$queryMode='All',$debug=false) { if($debug===true)$this->debug($strSql); $recordset=$this->dbh->query($strSql); $this->getPDOError(); if($recordset){ $recordset->setFetchMode(PDO::FETCH_ASSOC); if($queryMode=='All'){ $result=$recordset->fetchAll(); }elseif($queryMode=='Row'){ $result=$recordset->fetch(); } }else{ $result=null; } return$result; } /** *Update更新 * *@paramString$table表名 *@paramArray$arrayDataValue字段与值 *@paramString$where条件 *@paramBoolean$debug *@returnInt */ publicfunctionupdate($table,$arrayDataValue,$where='',$debug=false) { $this->checkFields($table,$arrayDataValue); if($where){ $strSql=''; foreach($arrayDataValueas$key=>$value){ $strSql.=",`$key`='$value'"; } $strSql=substr($strSql,1); $strSql="UPDATE`$table`SET$strSqlWHERE$where"; }else{ $strSql="REPLACEINTO`$table`(`".implode('`,`',array_keys($arrayDataValue))."`)VALUES('".implode("','",$arrayDataValue)."')"; } if($debug===true)$this->debug($strSql); $result=$this->dbh->exec($strSql); $this->getPDOError(); return$result; } /** *Insert插入 * *@paramString$table表名 *@paramArray$arrayDataValue字段与值 *@paramBoolean$debug *@returnInt */ publicfunctioninsert($table,$arrayDataValue,$debug=false) { $this->checkFields($table,$arrayDataValue); $strSql="INSERTINTO`$table`(`".implode('`,`',array_keys($arrayDataValue))."`)VALUES('".implode("','",$arrayDataValue)."')"; if($debug===true)$this->debug($strSql); $result=$this->dbh->exec($strSql); $this->getPDOError(); return$result; } /** *Replace覆盖方式插入 * *@paramString$table表名 *@paramArray$arrayDataValue字段与值 *@paramBoolean$debug *@returnInt */ publicfunctionreplace($table,$arrayDataValue,$debug=false) { $this->checkFields($table,$arrayDataValue); $strSql="REPLACEINTO`$table`(`".implode('`,`',array_keys($arrayDataValue))."`)VALUES('".implode("','",$arrayDataValue)."')"; if($debug===true)$this->debug($strSql); $result=$this->dbh->exec($strSql); $this->getPDOError(); return$result; } /** *Delete删除 * *@paramString$table表名 *@paramString$where条件 *@paramBoolean$debug *@returnInt */ publicfunctiondelete($table,$where='',$debug=false) { if($where==''){ $this->outputError("'WHERE'isNull"); }else{ $strSql="DELETEFROM`$table`WHERE$where"; if($debug===true)$this->debug($strSql); $result=$this->dbh->exec($strSql); $this->getPDOError(); return$result; } } /** *execSql执行SQL语句 * *@paramString$strSql *@paramBoolean$debug *@returnInt */ publicfunctionexecSql($strSql,$debug=false) { if($debug===true)$this->debug($strSql); $result=$this->dbh->exec($strSql); $this->getPDOError(); return$result; } /** *获取字段最大值 * *@paramstring$table表名 *@paramstring$field_name字段名 *@paramstring$where条件 */ publicfunctiongetMaxValue($table,$field_name,$where='',$debug=false) { $strSql="SELECTMAX(".$field_name.")ASMAX_VALUEFROM$table"; if($where!='')$strSql.="WHERE$where"; if($debug===true)$this->debug($strSql); $arrTemp=$this->query($strSql,'Row'); $maxValue=$arrTemp["MAX_VALUE"]; if($maxValue==""||$maxValue==null){ $maxValue=0; } return$maxValue; } /** *获取指定列的数量 * *@paramstring$table *@paramstring$field_name *@paramstring$where *@parambool$debug *@returnint */ publicfunctiongetCount($table,$field_name,$where='',$debug=false) { $strSql="SELECTCOUNT($field_name)ASNUMFROM$table"; if($where!='')$strSql.="WHERE$where"; if($debug===true)$this->debug($strSql); $arrTemp=$this->query($strSql,'Row'); return$arrTemp['NUM']; } /** *获取表引擎 * *@paramString$dbName库名 *@paramString$tableName表名 *@paramBoolean$debug *@returnString */ publicfunctiongetTableEngine($dbName,$tableName) { $strSql="SHOWTABLESTATUSFROM$dbNameWHEREName='".$tableName."'"; $arrayTableInfo=$this->query($strSql); $this->getPDOError(); return$arrayTableInfo[0]['Engine']; } /** *beginTransaction事务开始 */ privatefunctionbeginTransaction() { $this->dbh->beginTransaction(); } /** *commit事务提交 */ privatefunctioncommit() { $this->dbh->commit(); } /** *rollback事务回滚 */ privatefunctionrollback() { $this->dbh->rollback(); } /** *transaction通过事务处理多条SQL语句 *调用前需通过getTableEngine判断表引擎是否支持事务 * *@paramarray$arraySql *@returnBoolean */ publicfunctionexecTransaction($arraySql) { $retval=1; $this->beginTransaction(); foreach($arraySqlas$strSql){ if($this->execSql($strSql)==0)$retval=0; } if($retval==0){ $this->rollback(); returnfalse; }else{ $this->commit(); returntrue; } } /** *checkFields检查指定字段是否在指定数据表中存在 * *@paramString$table *@paramarray$arrayField */ privatefunctioncheckFields($table,$arrayFields) { $fields=$this->getFields($table); foreach($arrayFieldsas$key=>$value){ if(!in_array($key,$fields)){ $this->outputError("Unknowncolumn`$key`infieldlist."); } } } /** *getFields获取指定数据表中的全部字段名 * *@paramString$table表名 *@returnarray */ privatefunctiongetFields($table) { $fields=array(); $recordset=$this->dbh->query("SHOWCOLUMNSFROM$table"); $this->getPDOError(); $recordset->setFetchMode(PDO::FETCH_ASSOC); $result=$recordset->fetchAll(); foreach($resultas$rows){ $fields[]=$rows['Field']; } return$fields; } /** *getPDOError捕获PDO错误信息 */ privatefunctiongetPDOError() { if($this->dbh->errorCode()!='00000'){ $arrayError=$this->dbh->errorInfo(); $this->outputError($arrayError[2]); } } /** *debug * *@parammixed$debuginfo */ privatefunctiondebug($debuginfo) { var_dump($debuginfo); exit(); } /** *输出错误信息 * *@paramString$strErrMsg */ privatefunctionoutputError($strErrMsg) { thrownewException('MySQLError:'.$strErrMsg); } /** *destruct关闭数据库连接 */ publicfunctiondestruct() { $this->dbh=null; } } ?>
四、调用方法:
<?php require'MyPDO.class.php'; $db=MyPDO::getInstance('localhost','root','123456','test','utf8'); //dosomething... $db->destruct(); ?>
五、总结
以上就是PHP基于单例模式编写PDO类的全部内容,希望对大家学习或者使用PHP能有所帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。