当前位置:首页 > PHP教程 > php高级应用 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2015-04-15 11:12:37 浏览: 评论:0 

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

  1. <?php 
  2.  
  3. class MyPDO 
  4. { 
  5.     protected static $_instance = null; 
  6.     protected $dbName = ''; 
  7.     protected $dsn; 
  8.     protected $dbh; 
  9.      
  10.     /** 
  11.      * 构造 
  12.      *  
  13.      * @return MyPDO 
  14.      */ 
  15.     private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset) 
  16.     { 
  17.         try { 
  18.             $this->dsn = 'mysql:host='.$dbHost.';dbname='.$dbName; 
  19.             $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd); 
  20.             $this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary'); 
  21.         } catch (PDOException $e) { 
  22.             $this->outputError($e->getMessage()); 
  23.         } 
  24.     } 
  25.      
  26.     /** 
  27.      * 防止克隆 
  28.      *  
  29.      */ 
  30.     private function __clone() {} 
  31.      
  32.     /** 
  33.      * Singleton instance 
  34.      *  
  35.      * @return Object 
  36.      */ 
  37.     public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset) 
  38.     { 
  39.         if (self::$_instance === null) { 
  40.             self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset); 
  41.         } 
  42.         return self::$_instance; 
  43.     } 
  44.      
  45.     /** 
  46.      * Query 查询 
  47.      * 
  48.      * @param String $strSql SQL语句 
  49.      * @param String $queryMode 查询方式(All or Row) 
  50.      * @param Boolean $debug 
  51.      * @return Array 
  52.      */ 
  53.     public function query($strSql, $queryMode = 'All', $debug = false) 
  54.     { 
  55.         if ($debug === true) $this->debug($strSql); 
  56.         $recordset = $this->dbh->query($strSql); 
  57.         $this->getPDOError(); 
  58.         if ($recordset) { 
  59.             $recordset->setFetchMode(PDO::FETCH_ASSOC); 
  60.             if ($queryMode == 'All') { 
  61.                 $result = $recordset->fetchAll(); 
  62.             } elseif ($queryMode == 'Row') { 
  63.                 $result = $recordset->fetch(); 
  64.             } 
  65.         } else { 
  66.             $result = null; 
  67.         } 
  68.         return $result; 
  69.     } 
  70.      
  71.     /** 
  72.      * Update 更新 
  73.      * 
  74.      * @param String $table 表名 
  75.      * @param Array $arrayDataValue 字段与值 
  76.      * @param String $where 条件 
  77.      * @param Boolean $debug 
  78.      * @return Int 
  79.      */ 
  80.     public function update($table, $arrayDataValue, $where = '', $debug = false) 
  81.     { 
  82.         $this->checkFields($table, $arrayDataValue); 
  83.         if ($where) { 
  84.             $strSql = ''; 
  85.             foreach ($arrayDataValue as $key => $value) { 
  86.                 $strSql .= ", `$key`='$value'"; 
  87.             } 
  88.             $strSql = substr($strSql, 1); 
  89.             $strSql = "UPDATE `$table` SET $strSql WHERE $where"; 
  90.         } else { 
  91.             $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')"; 
  92.         } 
  93.         if ($debug === true) $this->debug($strSql); 
  94.         $result = $this->dbh->exec($strSql); 
  95.         $this->getPDOError(); 
  96.         return $result; 
  97.     } 
  98.      
  99.     /** 
  100.      * Insert 插入 
  101.      * 
  102.      * @param String $table 表名 
  103.      * @param Array $arrayDataValue 字段与值 
  104.      * @param Boolean $debug 
  105.      * @return Int 
  106.      */ 
  107.     public function insert($table, $arrayDataValue, $debug = false) 
  108.     { 
  109.         $this->checkFields($table, $arrayDataValue); 
  110.         $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')"; 
  111.         if ($debug === true) $this->debug($strSql); 
  112.         $result = $this->dbh->exec($strSql); 
  113.         $this->getPDOError(); 
  114.         return $result; 
  115.     } 
  116.      
  117.     /** 
  118.      * Replace 覆盖方式插入 
  119.      * 
  120.      * @param String $table 表名 
  121.      * @param Array $arrayDataValue 字段与值 
  122.      * @param Boolean $debug 
  123.      * @return Int 
  124.      */ 
  125.     public function replace($table, $arrayDataValue, $debug = false) 
  126.     { 
  127.         $this->checkFields($table, $arrayDataValue); 
  128.         $strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')"; 
  129.         if ($debug === true) $this->debug($strSql); 
  130.         $result = $this->dbh->exec($strSql); 
  131.         $this->getPDOError(); 
  132.         return $result; 
  133.     } 
  134.      
  135.     /** 
  136.      * Delete 删除 
  137.      * 
  138.      * @param String $table 表名 
  139.      * @param String $where 条件 
  140.      * @param Boolean $debug 
  141.      * @return Int 
  142.      */ 
  143.     public function delete($table, $where = '', $debug = false) 
  144.     { 
  145.         if ($where == '') { 
  146.             $this->outputError("'WHERE' is Null"); 
  147.         } else { 
  148.             $strSql = "DELETE FROM `$table` WHERE $where"; 
  149.             if ($debug === true) $this->debug($strSql); 
  150.             $result = $this->dbh->exec($strSql); 
  151.             $this->getPDOError(); 
  152.             return $result; 
  153.         } 
  154.     } 
  155.      
  156.     /** 
  157.      * execSql 执行SQL语句 
  158.      * 
  159.      * @param String $strSql 
  160.      * @param Boolean $debug 
  161.      * @return Int 
  162.      */ 
  163.     public function execSql($strSql, $debug = false) 
  164.     { 
  165.         if ($debug === true) $this->debug($strSql); 
  166.         $result = $this->dbh->exec($strSql); 
  167.         $this->getPDOError(); 
  168.         return $result; 
  169.     } 
  170.      
  171.     /** 
  172.      * 获取字段最大值 
  173.      *  
  174.      * @param string $table 表名 
  175.      * @param string $field_name 字段名 
  176.      * @param string $where 条件 
  177.      */ 
  178.     public function getMaxValue($table, $field_name, $where = '', $debug = false) 
  179.     { 
  180.         $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table"; 
  181.         if ($where != '') $strSql .= " WHERE $where"; 
  182.         if ($debug === true) $this->debug($strSql); 
  183.         $arrTemp = $this->query($strSql, 'Row'); 
  184.         $maxValue = $arrTemp["MAX_VALUE"]; 
  185.         if ($maxValue == "" || $maxValue == null) { 
  186.             $maxValue = 0; 
  187.         } 
  188.         return $maxValue; 
  189.     } 
  190.      
  191.     /** 
  192.      * 获取指定列的数量 
  193.      *  
  194.      * @param string $table 
  195.      * @param string $field_name 
  196.      * @param string $where 
  197.      * @param bool $debug 
  198.      * @return int 
  199.      */ 
  200.     public function getCount($table, $field_name, $where = '', $debug = false) 
  201.     { 
  202.         $strSql = "SELECT COUNT($field_name) AS NUM FROM $table"; 
  203.         if ($where != '') $strSql .= " WHERE $where"; 
  204.         if ($debug === true) $this->debug($strSql); 
  205.         $arrTemp = $this->query($strSql, 'Row'); 
  206.         return $arrTemp['NUM']; 
  207.     } 
  208.      
  209.     /** 
  210.      * 获取表引擎 
  211.      *  
  212.      * @param String $dbName 库名 
  213.      * @param String $tableName 表名 
  214.      * @param Boolean $debug 
  215.      * @return String 
  216.      */ 
  217.     public function getTableEngine($dbName, $tableName) 
  218.     { 
  219.         $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='".$tableName."'"; 
  220.         $arrayTableInfo = $this->query($strSql); 
  221.         $this->getPDOError(); 
  222.         return $arrayTableInfo[0]['Engine']; 
  223.     } 
  224.      
  225.     /** 
  226.      * beginTransaction 事务开始 
  227.      */ 
  228.     private function beginTransaction() 
  229.     { 
  230.         $this->dbh->beginTransaction(); 
  231.     } 
  232.      
  233.     /** 
  234.      * commit 事务提交 
  235.      */ 
  236.     private function commit() 
  237.     { 
  238.         $this->dbh->commit(); 
  239.     } 
  240.      
  241.     /** 
  242.      * rollback 事务回滚 
  243.      */ 
  244.     private function rollback() 
  245.     { 
  246.         $this->dbh->rollback(); 
  247.     } 
  248.      
  249.     /** 
  250.      * transaction 通过事务处理多条SQL语句 
  251.      * 调用前需通过getTableEngine判断表引擎是否支持事务 
  252.      * 
  253.      * @param array $arraySql 
  254.      * @return Boolean 
  255.      */ 
  256.     public function execTransaction($arraySql) 
  257.     { 
  258.         $retval = 1; 
  259.         $this->beginTransaction(); 
  260.         foreach ($arraySql as $strSql) { 
  261.             if ($this->execSql($strSql) == 0) $retval = 0; 
  262.         } 
  263.         if ($retval == 0) { 
  264.             $this->rollback(); 
  265.             return false; 
  266.         } else { 
  267.             $this->commit(); 
  268.             return true; 
  269.         } 
  270.     } 
  271.  
  272.     /** 
  273.      * checkFields 检查指定字段是否在指定数据表中存在 
  274.      * 
  275.      * @param String $table 
  276.      * @param array $arrayField 
  277.      */ 
  278.     private function checkFields($table, $arrayFields) 
  279.     { 
  280.         $fields = $this->getFields($table); 
  281.         foreach ($arrayFields as $key => $value) { 
  282.             if (!in_array($key, $fields)) { 
  283.                 $this->outputError("Unknown column `$key` in field list."); 
  284.             } 
  285.         } 
  286.     } 
  287.      
  288.     /** 
  289.      * getFields 获取指定数据表中的全部字段名 
  290.      * 
  291.      * @param String $table 表名 
  292.      * @return array 
  293.      */ 
  294.     private function getFields($table) 
  295.     { 
  296.         $fields = array(); 
  297.         $recordset = $this->dbh->query("SHOW COLUMNS FROM $table"); 
  298.         $this->getPDOError(); 
  299.         $recordset->setFetchMode(PDO::FETCH_ASSOC); 
  300.         $result = $recordset->fetchAll(); 
  301.         foreach ($result as $rows) { 
  302.             $fields[] = $rows['Field']; 
  303.         } 
  304.         return $fields; 
  305.     } 
  306.      
  307.     /** 
  308.      * getPDOError 捕获PDO错误信息 
  309.      */ 
  310.     private function getPDOError() 
  311.     { 
  312.         if ($this->dbh->errorCode() != '00000') { 
  313.             $arrayError = $this->dbh->errorInfo(); 
  314.             $this->outputError($arrayError[2]); 
  315.         } 
  316.     } 
  317.      
  318.     /** 
  319.      * debug 
  320.      *  
  321.      * @param mixed $debuginfo 
  322.      */ 
  323.     private function debug($debuginfo) 
  324.     { 
  325.         var_dump($debuginfo); 
  326.         exit(); 
  327.     } 
  328.      
  329.     /** 
  330.      * 输出错误信息 
  331.      *  
  332.      * @param String $strErrMsg 
  333.      */ 
  334.     private function outputError($strErrMsg) 
  335.     { 
  336.         throw new Exception('MySQL Error: '.$strErrMsg); 
  337.     }  //开源软件:phpfensi.com 
  338.      
  339.     /** 
  340.      * destruct 关闭数据库连接 
  341.      */ 
  342.     public function destruct() 
  343.     { 
  344.         $this->dbh = null; 
  345.     } 
  346. } 
  347. ?> 

调用方法:

  1. <?php 
  2. require 'MyPDO.class.php'; 
  3. $db = MyPDO::getInstance('localhost', 'root', '123456', 'test', 'utf8'); 
  4.  
  5. //do something... 
  6.  
  7. $db->destruct(); 
  8. ?>

Tags: PHP单例模式 PDO类程序

分享到: