我有以下课程:
<?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
现在我有了第二个类,它具有访问数据库的所有功能。
我的问题:
我的脚本中有最大连接问题,因此我使用新的Database类。在我的助手课程中,我这样做:
<?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()
,因为这总是会创建一个新的数据库连接,对吧?
感谢您的帮助!
答案 0 :(得分:1)
这并不重要。
只要您使用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
}
}