我有以下课程:
<?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;
在每个函数中一样访问它并尝试?
有什么更好的方法可以避免与我的数据库建立过多的连接?
并且在文件中初始化一次助手类肯定更好,对吧?并不总是打电话$helper = new helper()
,因为这总是会创建一个新的数据库连接,对吧?
谢谢您的帮助!