侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

php  /  管理员 发布于 7年前   181

一、单例模式简介

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

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

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

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

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

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

代码如下:

 * @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; }}?>

四、调用方法:

destruct();?>

五、总结

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

您可能感兴趣的文章:

  • PHP单例模式数据库连接类与页面静态化实现方法
  • PHP中数据库单例模式的实现代码分享
  • PHP基于单例模式实现的数据库操作基类
  • PHP单例模式应用示例【多次连接数据库只实例化一次】
  • PHP实现单例模式最安全的做法
  • php单例模式的简单实现方法
  • php利用单例模式实现日志处理类库
  • PHP最常用的2种设计模式工厂模式和单例模式介绍
  • PHP设计模式之工厂模式与单例模式
  • PHP实现单例模式建立数据库连接的方法分析


  • 上一条:
    PHP经典算法集锦【经典收藏】
    下一条:
    利用PHP将图片转换成base64编码的实现方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客