NEWS CENTER

资讯中心

小二CMS · 专注企业数字化转型的资讯与干货

PHP单例模式编写的PDO类的程序

748 阅读 字号
下面的代码是用此前一个名为MyPDO的类改写的,引入了单例模式来保证在全局调用中不会重复实例化这个类,降低系统资源的浪费。
用php大部分操作都是和各种数据库打交道,包括mysql,redis,memcache等各种关系型和非关系型数据库,所以一个应用中会 存在大量连接数据库的操作,如果不用单例模式,那每次都要new操作,但是每次new都会消耗大量的内存资源和系统资源,而且每次打开和关闭数据库连接都 是对数据库的一种极大考验和浪费
代码如下:
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类的程序

文章内容来源于网络,文章表达观点不代表本站观点,文章版权归原作者所有。若有侵权,请联系本站站长处理!

小二CMS介绍

我们立足合肥,业务覆盖安徽、全国及全球市场。我们凭借一支经验丰富、富有创意、协作无间的专业技术团队,专注于将前沿技术通过高效简捷的途径呈现给客户,量身打造优质解决方案。我们致力于通过持续努力,成为客户在信息化领域值得托付、共创价值的长期战略合作伙伴,协助客户在新经济时代敏锐捕捉商机,拓展发展空间,构筑强大竞争力。小二CMS专注企业数字化转型的智能建站与营销系统,提供从官网搭建、品牌推广到运营增长的一站式服务,助力中小企业低门槛拥有专业级互联网阵地。

了解全部业务
小二CMS微信二维码
扫码咨询 · 关注微信

这篇文章对你有帮助吗?

你的每一次鼓励,都是我们持续打磨优质内容的动力

ABOUT US

关于我们

以 AI 驱动创新,以品质铸造口碑

关于我们

小二CMS一家融合AI人工智能与前沿互联网技术的数字化解决方案服务商,专注于高端网站建设、微信小程序开发、移动端应用研发及企业数字化转型服务。我们将AI技术深度融入产品研发与服务流程,通过智能算法、大模型应用与自动化工具,为客户提供更高效、更精准的数字化解决方案。

自2013年成立以来,我们已成功交付3000+个精品项目,服务客户遍布金融、零售、制造、教育、医疗、互联网等多个行业领域。我们拥有资深的技术团队与丰富的实战经验,在AI智能应用、复杂业务建模、高性能架构设计、跨平台开发及企业级安全保障等方面具备专业能力。

我们相信,AI不是替代人,而是赋能人。选择小二CMS,就是选择一支懂技术、懂AI、更懂您业务痛点的数字化创新团队。让我们以AI之力,将您的品牌愿景与市场机遇转化为可落地的数字现实,共同驱动业务增长与品牌价值升级。

3000+ 精品项目 13年 行业深耕 98% 客户满意
我们的优势
01
AI深度融合大模型+智能自动化
02
十三年深耕专注高端网站建设
03
全栈技术能力前后端+跨平台开发
04
资深策划团队深度洞悉行业需求
05
SEO深度优化搜索引擎友好排名
06
完善售后体系全程无忧技术支持
07
数据安全保障多重防护体系
08
弹性架构灵活支持二次开发
我们的不同

我们是一支充满激情与创造力的团队,痴迷代码,沉醉设计,深耕AI技术。我们坚信:技术不是冰冷的工具,而是驱动商业增长的核动力。

AI先行

将AI融入产品与服务全流程

品质至上

客户第一,追求卓越用户体验

彼此成就

客户的成功,才是我们真正的成功

产品演示

产品演示二维码

请使用微信扫描二维码

查看产品演示

QQ 客服

扫码添加好友 · 专属客服在线

QQ二维码
QQ号:460623785

微信客服

扫码添加 · 一对一专属服务

微信二维码
微信号:yanboss0901
PROFESSIONAL SERVICE

联系我们

选择最适合您的方式 · 专属顾问 7×24 在线为您服务

微信客服

扫码添加 · 一对一专属服务

微信二维码
微信号 yanboss0901

QQ 客服

扫码添加 · 专属客服在线

QQ二维码
QQ号 460623785

电话咨询

工作日 9:00-21:00 · 极速响应

立即拨打

在线客服

智能 + 人工 · 即时沟通

遇到问题?点击进入在线客服,智能助手与人工顾问随时为您解答。

进入在线客服
在线客服
电话咨询
微信咨询
QQ咨询

电话咨询

点击拨打 · 专属顾问为您解答

咨询热线19810950281
服务时间:周一至周日 9:00 - 21:00
回到顶部
预约演示 · FREE DEMO

预约产品演示

留下联系方式,顾问将尽快为您安排一对一演示

信息严格保密,仅用于与您联系

提交成功

我们已收到您的预约,顾问将尽快与您联系。