PHP基于单例模式编写PDO类的方法


Posted in PHP onSeptember 13, 2016

一、单例模式简介

简单的说,一个对象(在学习设计模式之前,需要比较了解面向对象思想)只负责一个特定的任务;

二、为什么要使用PHP单例模式?

     1、php的应用主要在于数据库应用, 所以一个应用中会存在大量的数据库操作, 使用单例模式, 则可以避免大量的new 操作消耗的资源。

     2、如果系统中需要有一个类来全局控制某些配置信息, 那么使用单例模式可以很方便的实现. 这个可以参看ZF的FrontController部分。

     3、在一次页面请求中, 便于进行调试, 因为所有的代码(例如数据库操作类db)都集中在一个类中, 我们可以在类中设置钩子, 输出日志,从而避免到处var_dump, echo

三、PHP基于单例模式编写PDO类的示例代码

代码如下:

<?php
/**
 * MyPDO
 * @author Jason.Wei <jasonwei06@hotmail.com>
 * @license http://www.sunbloger.com/
 * @version 5.0 utf8
 */
class MyPDO
{
 protected static $_instance = null;
 protected $dbName = '';
 protected $dsn;
 protected $dbh;
 
 /**
  * 构造
  * 
  * @return MyPDO
  */
 private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
 {
  try {
   $this->dsn = 'mysql:host='.$dbHost.';dbname='.$dbName;
   $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
   $this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');
  } catch (PDOException $e) {
   $this->outputError($e->getMessage());
  }
 }
 
 /**
  * 防止克隆
  * 
  */
 private function __clone() {}
 
 /**
  * Singleton instance
  * 
  * @return Object
  */
 public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
 {
  if (self::$_instance === null) {
   self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
  }
  return self::$_instance;
 }
 
 /**
  * Query 查询
  *
  * @param String $strSql SQL语句
  * @param String $queryMode 查询方式(All or Row)
  * @param Boolean $debug
  * @return Array
  */
 public function query($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 更新
  *
  * @param String $table 表名
  * @param Array $arrayDataValue 字段与值
  * @param String $where 条件
  * @param Boolean $debug
  * @return Int
  */
 public function update($table, $arrayDataValue, $where = '', $debug = false)
 {
  $this->checkFields($table, $arrayDataValue);
  if ($where) {
   $strSql = '';
   foreach ($arrayDataValue as $key => $value) {
    $strSql .= ", `$key`='$value'";
   }
   $strSql = substr($strSql, 1);
   $strSql = "UPDATE `$table` SET $strSql WHERE $where";
  } else {
   $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
  }
  if ($debug === true) $this->debug($strSql);
  $result = $this->dbh->exec($strSql);
  $this->getPDOError();
  return $result;
 }
 
 /**
  * Insert 插入
  *
  * @param String $table 表名
  * @param Array $arrayDataValue 字段与值
  * @param Boolean $debug
  * @return Int
  */
 public function insert($table, $arrayDataValue, $debug = false)
 {
  $this->checkFields($table, $arrayDataValue);
  $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
  if ($debug === true) $this->debug($strSql);
  $result = $this->dbh->exec($strSql);
  $this->getPDOError();
  return $result;
 }
 
 /**
  * Replace 覆盖方式插入
  *
  * @param String $table 表名
  * @param Array $arrayDataValue 字段与值
  * @param Boolean $debug
  * @return Int
  */
 public function replace($table, $arrayDataValue, $debug = false)
 {
  $this->checkFields($table, $arrayDataValue);
  $strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
  if ($debug === true) $this->debug($strSql);
  $result = $this->dbh->exec($strSql);
  $this->getPDOError();
  return $result;
 }
 
 /**
  * Delete 删除
  *
  * @param String $table 表名
  * @param String $where 条件
  * @param Boolean $debug
  * @return Int
  */
 public function delete($table, $where = '', $debug = false)
 {
  if ($where == '') {
   $this->outputError("'WHERE' is Null");
  } else {
   $strSql = "DELETE FROM `$table` WHERE $where";
   if ($debug === true) $this->debug($strSql);
   $result = $this->dbh->exec($strSql);
   $this->getPDOError();
   return $result;
  }
 }
 
 /**
  * execSql 执行SQL语句
  *
  * @param String $strSql
  * @param Boolean $debug
  * @return Int
  */
 public function execSql($strSql, $debug = false)
 {
  if ($debug === true) $this->debug($strSql);
  $result = $this->dbh->exec($strSql);
  $this->getPDOError();
  return $result;
 }
 
 /**
  * 获取字段最大值
  * 
  * @param string $table 表名
  * @param string $field_name 字段名
  * @param string $where 条件
  */
 public function getMaxValue($table, $field_name, $where = '', $debug = false)
 {
  $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $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;
 }
 
 /**
  * 获取指定列的数量
  * 
  * @param string $table
  * @param string $field_name
  * @param string $where
  * @param bool $debug
  * @return int
  */
 public function getCount($table, $field_name, $where = '', $debug = false)
 {
  $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
  if ($where != '') $strSql .= " WHERE $where";
  if ($debug === true) $this->debug($strSql);
  $arrTemp = $this->query($strSql, 'Row');
  return $arrTemp['NUM'];
 }
 
 /**
  * 获取表引擎
  * 
  * @param String $dbName 库名
  * @param String $tableName 表名
  * @param Boolean $debug
  * @return String
  */
 public function getTableEngine($dbName, $tableName)
 {
  $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='".$tableName."'";
  $arrayTableInfo = $this->query($strSql);
  $this->getPDOError();
  return $arrayTableInfo[0]['Engine'];
 }
 
 /**
  * beginTransaction 事务开始
  */
 private function beginTransaction()
 {
  $this->dbh->beginTransaction();
 }
 
 /**
  * commit 事务提交
  */
 private function commit()
 {
  $this->dbh->commit();
 }
 
 /**
  * rollback 事务回滚
  */
 private function rollback()
 {
  $this->dbh->rollback();
 }
 
 /**
  * transaction 通过事务处理多条SQL语句
  * 调用前需通过getTableEngine判断表引擎是否支持事务
  *
  * @param array $arraySql
  * @return Boolean
  */
 public function execTransaction($arraySql)
 {
  $retval = 1;
  $this->beginTransaction();
  foreach ($arraySql as $strSql) {
   if ($this->execSql($strSql) == 0) $retval = 0;
  }
  if ($retval == 0) {
   $this->rollback();
   return false;
  } else {
   $this->commit();
   return true;
  }
 }
 
 /**
  * checkFields 检查指定字段是否在指定数据表中存在
  *
  * @param String $table
  * @param array $arrayField
  */
 private function checkFields($table, $arrayFields)
 {
  $fields = $this->getFields($table);
  foreach ($arrayFields as $key => $value) {
   if (!in_array($key, $fields)) {
    $this->outputError("Unknown column `$key` in field list.");
   }
  }
 }
 
 /**
  * getFields 获取指定数据表中的全部字段名
  *
  * @param String $table 表名
  * @return array
  */
 private function getFields($table)
 {
  $fields = array();
  $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
  $this->getPDOError();
  $recordset->setFetchMode(PDO::FETCH_ASSOC);
  $result = $recordset->fetchAll();
  foreach ($result as $rows) {
   $fields[] = $rows['Field'];
  }
  return $fields;
 }
 
 /**
  * getPDOError 捕获PDO错误信息
  */
 private function getPDOError()
 {
  if ($this->dbh->errorCode() != '00000') {
   $arrayError = $this->dbh->errorInfo();
   $this->outputError($arrayError[2]);
  }
 }
 
 /**
  * debug
  * 
  * @param mixed $debuginfo
  */
 private function debug($debuginfo)
 {
  var_dump($debuginfo);
  exit();
 }
 
 /**
  * 输出错误信息
  * 
  * @param String $strErrMsg
  */
 private function outputError($strErrMsg)
 {
  throw new Exception('MySQL Error: '.$strErrMsg);
 }
 
 /**
  * destruct 关闭数据库连接
  */
 public function destruct()
 {
  $this->dbh = null;
 }
}
?>

四、调用方法:

<?php
require 'MyPDO.class.php';
$db = MyPDO::getInstance('localhost', 'root', '123456', 'test', 'utf8');
 
//do something...
 
$db->destruct();
?>

五、总结

以上就是PHP基于单例模式编写PDO类的全部内容,希望对大家学习或者使用PHP能有所帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

PHP 相关文章推荐
第七章 php自定义函数实现代码
Dec 30 PHP
PHP goto语句简介和使用实例
Mar 11 PHP
phpmyadmin打开很慢的解决方法
Apr 21 PHP
ThinkPHP中的系统常量和预定义常量集合
Jul 01 PHP
使用PHP和JavaScript判断请求是否来自微信内浏览器
Aug 18 PHP
PHP模板引擎Smarty中变量的使用方法示例
Apr 11 PHP
PHP实现超简单的SSL加密解密、验证及签名的方法示例
Aug 28 PHP
利用Homestead快速运行一个Laravel项目的方法详解
Nov 14 PHP
PHP实现十进制数字与二十六进制字母串相互转换操作示例
Aug 10 PHP
PHP htmlspecialchars_decode()函数用法讲解
Mar 01 PHP
PHP+Ajax简单get验证操作示例
Mar 02 PHP
Thinkphp5框架ajax接口实现方法分析
Aug 28 PHP
利用PHP将图片转换成base64编码的实现方法
Sep 13 #PHP
PHP将URL转换成短网址的算法分享
Sep 13 #PHP
PHP使用FFmpeg获取视频播放总时长与码率等信息
Sep 13 #PHP
php微信公众平台开发之微信群发信息
Sep 13 #PHP
PHP入门教程之使用Mysqli操作数据库的方法(连接,查询,事务回滚等)
Sep 11 #PHP
PHP入门教程之面向对象的特性分析(继承,多态,接口,抽象类,抽象方法等)
Sep 11 #PHP
PHP入门教程之面向对象基本概念实例分析
Sep 11 #PHP
You might like
PHP+MySQL 手工注入语句大全 推荐
2009/10/30 PHP
Codeigniter整合Tank Auth权限类库详解
2014/06/12 PHP
php提取字符串中网站url地址的方法
2014/12/03 PHP
PHP观察者模式原理与简单实现方法示例
2017/08/25 PHP
PHP获取HTTP body内容的方法
2018/12/31 PHP
高亮显示web页表格行的javascript代码
2010/11/19 Javascript
基于jquery的lazy loader插件实现图片的延迟加载[简单使用]
2011/05/07 Javascript
JavaScript中对循环语句的优化技巧深入探讨
2014/06/06 Javascript
PHP+jQuery+Ajax+Mysql如何实现发表心情功能
2015/08/06 Javascript
jQuery中$(function() {});问题详解
2015/08/10 Javascript
jQuery鼠标悬浮链接弹出跟随图片实例代码
2016/01/08 Javascript
javascript如何实现360度全景照片问题汇总
2016/04/04 Javascript
浅谈JavaScript中数组的增删改查
2016/06/20 Javascript
jQuery插件dataTables添加序号列的方法
2016/07/06 Javascript
简单的渐变轮播插件
2017/01/12 Javascript
webpack配置导致字体图标无法显示的解决方法
2018/03/06 Javascript
webpack+vue-cli项目中引入外部非模块格式js的方法
2018/09/28 Javascript
angular6的响应式表单的实现
2018/10/10 Javascript
JS实现checkbox互斥(单选)功能示例
2019/05/04 Javascript
Vue项目总结之webpack常规打包优化方案
2019/06/06 Javascript
Python2实现的LED大数字显示效果示例
2017/09/04 Python
matplotlib给子图添加图例的方法
2018/08/03 Python
Python利用ORM控制MongoDB(MongoEngine)的步骤全纪录
2018/09/13 Python
python3.6 如何将list存入txt后再读出list的方法
2019/07/02 Python
使用tensorflow实现矩阵分解方式
2020/02/07 Python
Python使用monkey.patch_all()解决协程阻塞问题
2020/04/15 Python
弄清Pytorch显存的分配机制
2020/12/10 Python
python 基于opencv操作摄像头
2020/12/24 Python
CSS3中几个新增加的盒模型属性使用教程
2016/03/01 HTML / CSS
诗狄娜化妆品官方网站:Stila Cosmetics
2016/12/21 全球购物
KIKO MILANO俄罗斯官网:意大利领先的化妆品和护肤品品牌
2021/01/09 全球购物
汽车制造与装配专业自荐信范文
2014/01/02 职场文书
yy司仪主持词
2014/03/22 职场文书
优秀团支部申报材料
2014/12/26 职场文书
团员自我评价范文
2015/03/10 职场文书
社会实践心得体会范文
2016/01/14 职场文书