最近几天,我一直在与PDO交流,我正在开发一个小型CMS系统,以自学OOP技能,但是即使它只是一个小型CMS,我也希望它能够处理任何网络上的操作扔给它.
到目前为止,这就是我要提出的内容,我将向构造函数添加连接池,以根据需要启用大量并发连接.我对OOP知识还很陌生,因此我需要一些建议和批评,毫无疑问,我在这里做错了非常严重的事情.
尽管我添加了一个私有构造函数,因为我想在整个类中使用$this-> dbConnectionInstance来使用许多辅助函数,但我还是将Global or Singleton for database connection?作为基础设计.
非常感谢您的宝贵时间,如果您能给我任何建议,我将不胜感激,
-画
// 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;
}
}
?>
最佳答案
看起来不错,我将添加rollback功能以及缓冲的查询/ errorInfo建议(如果您使用的是支持事务的RDBMS):
try {
$this->dbConnectionInstance->beginTransaction();
$stmt = $this->dbConnectionInstance->prepare($sql);
$stmt->execute($params);
$this->dbConnectionInstance->commit();
}catch(PDOException $e){
$this->dbConnectionInstance->rollback();
}
> mysql performance blog
> pdo mysql buffered query support
> stack overflow: pdo buffered query problem