我有这个 PDO 连接类吗?

发布于 2024-08-08 21:09:03 字数 2339 浏览 0 评论 0原文

过去几天我一直在玩 PDO,我正在开发一个小型 CMS 系统来自学 OOP 技能,但即使它只是一个小型 CMS,我希望它能够处理网络可以处理的任何事情扔向它。

这是我到目前为止所想到的,我将向构造函数添加连接池,以按需启用大量并发连接。我对 OOP 的东西很陌生,所以我需要一些建议和批评,毫无疑问我在这里做了一些非常错误的事情。

我将 数据库连接是全局还是单例? 的最佳答案作为基础设计,尽管我添加了一个私有构造函数,因为我想在整个类中使用 $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;
    }

}

?>

谢谢你们的建议,我现在已经将回滚和提交添加到我的异常处理中,我只是在研究缓冲的使用查询,我不完全确定这会给我带来什么?

I've been playing around with PDO for the last few days, I'm working on a small CMS system to teach myself OOP skills, but even though it's only a small CMS, I want it to be able to handle whatever the web can throw at it.

This is what I've come up with so far, I'm going to add connection pooling to the constructor to enable large amounts of concurrent connects on demand. I'm very new to this OOP stuff so I'm wanting a little advise and critism, no doubt I've done something terribly wrong here.

I took the top answer to Global or Singleton for database connection? as the base design, although I've added a private constructor as I want to use $this->dbConnectionInstance throughout the class for numerous helper functions to use.

Thanks very much for your time, I really will appreciate any advise you can give me,

-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;
    }

}

?>

Thank you both for your suggestions, I've now added the rollback and commit into my exception handling, I'm just researching the use of buffered queries, I'm not entirely sure what ths will give me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠北森屋 2024-08-15 21:09:03

看起来不错,我会添加 回滚 功能以及缓冲查询/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()

编辑:添加了以下链接以获取有关缓冲查询的更多信息:

Looks good, I would add rollback functionality, along with the buffered query/errorInfo suggestions (If you're using a RDBMS that supports transactions):

try {
    $this->dbConnectionInstance->beginTransaction();
    $stmt = $this->dbConnectionInstance->prepare($sql);
    $stmt->execute($params);
    $this->dbConnectionInstance->commit();
}catch(PDOException $e){
    $this->dbConnectionInstance->rollback();
}

commit() , beginTransaction()

EDIT: added links below for more info on buffered queries:

死开点丶别碍眼 2024-08-15 21:09:03

你的代码看起来不太糟糕。但是,如果我可以做一些小的改变(主要是错误处理)。

如果发生错误,准备和执行语句都会返回 false。您可以从上面示例中的 $this->dbConnectionInstance->errorInfo() 访问错误。

另外,如果您计划使用任何大型查询,我建议使用缓冲查询: PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true

看起来是一个好的开始。祝您的 CMS 好运。

The code you have dosent look too bad. however if i could make a couple small changes (mainly error handling).

both the prepare and execute statements will return false on error. and you can access the error from $this->dbConnectionInstance->errorInfo() in your example above.

also if you plan on using any large queries I suggest using a buffered query: PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true

looks like a good start. Good luck on your CMS.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文