過去幾天我一直在玩PDO,我正在研究一個小的CMS系統來教自己的OOP技巧,但即使它只是一個小的CMS,我也希望它能夠處理任何網站可以拋出它。我有這個PDO連接類嗎?
這是我到目前爲止,我將添加連接池到構造函數,以啓用大量的併發連接點播。我對這個面向對象的東西很陌生,所以我想要一點建議和批評,毫無疑問,我在這裏做了一些非常錯誤的事情。
我將Global or Singleton for database connection?的最佳答案作爲基礎設計,儘管我已經添加了一個私有構造函數,因爲我希望在整個類中使用$ this-> dbConnectionInstance以使用許多輔助函數。
非常感謝您的時間,我真的會明白任何建議你可以給我,
-DREW
// Usage Example: $dbconn = dbManager::getConnection();
// $dbconn->query("SELECT * FROM accounts WHERE id=:id", "':id' => $id");
<?php
class dbManager {
private static $dbManagerInstance;
private $dbConnectionInstance;
private $stime;
private $etime;
public $timespent;
public $numqueries;
public $queries = array();
public static function getManager(){
if (!self::$dbManagerInstance){
self::$dbManagerInstance = new dbManager();
}
return self::$dbManagerInstance;
}
// Server details stored in definition file
private function __construct($db_server=DB_SERVER, $db_user=DB_USER, $db_pass=DB_PASS, $db_params=array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")) {
if(!$this->dbConnectionInstance)
{
try{
$this->dbConnectionInstance = new PDO($db_server, $db_user, $db_pass, $db_params);
$this->dbConnectionInstance->setAttribute(PDO::ATTR_PERSISTENT, PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$this->dbConnectionInstance = null;
die($e->getMessage());
}
}
return $this->dbConnectionInstance;
}
private function __destruct(){
$this->dbConnectionInstance = null;
}
private function query($sql, $params = array()) {
$this->queries[] = $sql;
$this->numqueries++;
$this->sTime = microtime();
$stmt = $this->dbConnectionInstance->prepare($sql);
$stmt->execute($params);
$this->eTime = microtime();
$this->timespent += round($this->eTime - $this->sTime, 4);
return $stmt;
}
}
?>
謝謝兩位你的建議,現在我已經加入回滾和提交到我的異常處理,我只是研究緩衝查詢的使用,我不完全確定會給我什麼?