最近几天,我一直在与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();
}
commit(),beginTransaction()
编辑:添加以下链接以获取有关缓冲查询的更多信息:
> mysql performance blog > pdo mysql buffered query support > stack overflow: pdo buffered query problem
(编辑:站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|