PDO Connections -最大连接数


PDO Connections - max connections

我有以下类:

<?php
class Database {
    protected static $_instance;
    protected $_connection;
    protected $_dbhost=DB_HOST;
    protected $_dbname=DB_DBNAME;
    protected $_username = DB_USER;
    protected $_password = DB_PASS;
    protected $_dbType = "mysql";
    /**
    * Singleton pattern implementation makes "new" unavailable
    */
    protected function __construct()
    {
        $this->_connection = 
            new PDO($this->_dbType . ":host=" . $this->_dbhost . ";dbname=" . $this->_dbname, $this->_username, $this->_password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", PDO::ATTR_PERSISTENT => true));
    }
    public function getConnection()
    {
        return $this->_connection;
    }
    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    /**
    * Singleton pattern implementation makes "clone" unavailable
    */
    protected function __clone()
    {}
}
?>  

From: https://stackoverflow.com/a/3010486

现在我有了第二个类,它具有访问DB的所有函数。

我的问题:
我在脚本中遇到了最大连接的问题,因此我使用了新的Database类。在我的helper类中,我是这样做的:

<?php   
class helper {
    function getAllInvitesFromPlayer($uid) {
        $sql = "SELECT request_id FROM ".DBPREFIX."invites WHERE inviter_id = :uid AND joined = 1";
        try {
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare($sql);
            $stmt->bindParam("uid", $uid);
            $stmt->execute();
            $content = $stmt->fetch(PDO::FETCH_LAZY);
            $db = null;
            return $content;
        } catch(PDOException $e) {
            echo $e->getMessage();
        }
    }
}

在"尝试"之后,使用$db = Database::getInstance()->getConnection();是正确的,还是我将其"外包"给一个类变量,并在每个函数中像$this->_db;一样访问它并尝试?
如何更好地避免对数据库的连接过多?

最好在文件中初始化一次helper类,对吗?并且不总是调用$helper = new helper(),因为这将总是创建一个新的DB连接,对吗?

谢谢你的帮助!

没关系。
只要您使用getInstance(),它将始终是相同的单个连接,无论您以哪种方式或在何处调用它。

为了封装,最好将db连接分配给一个类变量。

还要注意,try..catch的使用是错误的。它不应该在那里。

就像这样

<?php   
class helper {
    protected function __construct()
    {
        $this->db = Database::getInstance()->getConnection();
    }
    function getAllInvitesFromPlayer($uid) {
        $sql = "SELECT request_id FROM ".DBPREFIX."invites WHERE inviter_id = ? AND joined = 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($uid));
        return $stmt->fetchColumn(); // will return one invite actually
        //or
        return $stmt->fetchAll(PDO::FETCH_COLUMN, 0); // will return ALL invites indeed
    }
}