>  기사  >  백엔드 개발  >  PHP는 싱글톤 모드를 기반으로 PDO 클래스를 작성하는 방법을 구현합니다.

PHP는 싱글톤 모드를 기반으로 PDO 클래스를 작성하는 방법을 구현합니다.

墨辰丷
墨辰丷원래의
2018-06-01 11:22:091325검색

이 문서의 코드는 MyPDO라는 이전 클래스를 사용하여 다시 작성되었습니다. 싱글톤 모드는 이 클래스가 전역 호출에서 반복적으로 인스턴스화되지 않고 시스템 리소스 낭비를 줄이기 위해 도입되었습니다. 도움이 필요한 친구들이 참고할 수 있습니다. 아래를 살펴보겠습니다.

1. 싱글턴 패턴 소개

간단히 말해서 객체(디자인 패턴을 배우기 전에 객체 지향적 사고를 이해해야 함)는 특정 작업만 담당합니다.

2. 왜; ? PHP 싱글톤 패턴을 사용하시나요?

1. PHP 애플리케이션은 주로 데이터베이스 애플리케이션에 있으므로 애플리케이션에서 많은 수의 데이터베이스 작업이 발생합니다. 싱글톤 모드를 사용하면 새로운 작업에 많은 리소스가 소비되는 것을 피할 수 있습니다.

2. 시스템의 특정 구성 정보를 전역적으로 제어하기 위해 클래스가 필요한 경우 싱글톤 모드를 사용하여 쉽게 구현할 수 있습니다. 이는 ZF의 FrontController 섹션에서 찾을 수 있습니다. FrontController部分。

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

3. 페이지 요청에서는 모든 코드(예: 데이터베이스 작업 클래스 db)가 하나의 클래스에 집중되어 있기 때문에 디버깅하기 쉽습니다. 클래스에 후크를 설정하고 로그를 출력하여 를 피할 수 있습니다. 모든 곳에서 var_dump, echo. 3. 싱글톤 모드 기반 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 = &#39;&#39;;
 protected $dsn;
 protected $dbh;
 
 /**
  * 构造
  * 
  * @return MyPDO
  */
 private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset)
 {
  try {
   $this->dsn = &#39;mysql:host=&#39;.$dbHost.&#39;;dbname=&#39;.$dbName;
   $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
   $this->dbh->exec(&#39;SET character_set_connection=&#39;.$dbCharset.&#39;, character_set_results=&#39;.$dbCharset.&#39;, character_set_client=binary&#39;);
  } 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 = &#39;All&#39;, $debug = false)
 {
  if ($debug === true) $this->debug($strSql);
  $recordset = $this->dbh->query($strSql);
  $this->getPDOError();
  if ($recordset) {
   $recordset->setFetchMode(PDO::FETCH_ASSOC);
   if ($queryMode == &#39;All&#39;) {
    $result = $recordset->fetchAll();
   } elseif ($queryMode == &#39;Row&#39;) {
    $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 = &#39;&#39;, $debug = false)
 {
  $this->checkFields($table, $arrayDataValue);
  if ($where) {
   $strSql = &#39;&#39;;
   foreach ($arrayDataValue as $key => $value) {
    $strSql .= ", `$key`=&#39;$value&#39;";
   }
   $strSql = substr($strSql, 1);
   $strSql = "UPDATE `$table` SET $strSql WHERE $where";
  } else {
   $strSql = "REPLACE INTO `$table` (`".implode(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
  }
  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(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
  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(&#39;`,`&#39;, array_keys($arrayDataValue))."`) VALUES (&#39;".implode("&#39;,&#39;", $arrayDataValue)."&#39;)";
  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 = &#39;&#39;, $debug = false)
 {
  if ($where == &#39;&#39;) {
   $this->outputError("&#39;WHERE&#39; 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 = &#39;&#39;, $debug = false)
 {
  $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
  if ($where != &#39;&#39;) $strSql .= " WHERE $where";
  if ($debug === true) $this->debug($strSql);
  $arrTemp = $this->query($strSql, &#39;Row&#39;);
  $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 = &#39;&#39;, $debug = false)
 {
  $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
  if ($where != &#39;&#39;) $strSql .= " WHERE $where";
  if ($debug === true) $this->debug($strSql);
  $arrTemp = $this->query($strSql, &#39;Row&#39;);
  return $arrTemp[&#39;NUM&#39;];
 }
 
 /**
  * 获取表引擎
  * 
  * @param String $dbName 库名
  * @param String $tableName 表名
  * @param Boolean $debug
  * @return String
  */
 public function getTableEngine($dbName, $tableName)
 {
  $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name=&#39;".$tableName."&#39;";
  $arrayTableInfo = $this->query($strSql);
  $this->getPDOError();
  return $arrayTableInfo[0][&#39;Engine&#39;];
 }
 
 /**
  * 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[&#39;Field&#39;];
  }
  return $fields;
 }
 
 /**
  * getPDOError 捕获PDO错误信息
  */
 private function getPDOError()
 {
  if ($this->dbh->errorCode() != &#39;00000&#39;) {
   $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(&#39;MySQL Error: &#39;.$strErrMsg);
 }
 
 /**
  * destruct 关闭数据库连接
  */
 public function destruct()
 {
  $this->dbh = null;
 }
}
?>

4. 호출 방법:

rreee

요약: 위 내용이 이 글의 전체 내용입니다. 모든 분들의 공부에 도움이 되었으면 좋겠습니다.

관련 권장사항: php
기본적으로 Excel 파일을 내보내는 두 가지 방법에 대한 자세한 설명

php
2차원 배열 시간 정렬 구현

php
DOM 왜곡 해결 방법 D 코드

🎜🎜

위 내용은 PHP는 싱글톤 모드를 기반으로 PDO 클래스를 작성하는 방법을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.