0
我有下面的類:PDO連接 - 最大連接
<?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()
{}
}
?>
來源:https://stackoverflow.com/a/3010486
現在我有一個第二類,它具有所有訪問數據庫的功能。
我的問題:
我曾與我的腳本最大連接數的問題,所以我使用新的數據庫類。在我的輔助類我不喜歡這樣寫道:
<?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;
,並嘗試?
有什麼更好的方法來避免與我的db連接太多?
它肯定更好的只是在文件中初始化助手類,對吧?並不總是調用$helper = new helper()
,因爲這將始終創建一個新的數據庫連接,對吧?
謝謝你的幫助!