【发布时间】:2014-05-11 17:18:01
【问题描述】:
所以我对在 OOP 中连接到数据库的好方法做了一些研究。如果您在我的数据库模型中查看我的 connect() 方法,我只会在我即将查询 和 时才连接,如果还没有连接。我认为它被称为 惰性连接,我在 SO answer 上偶然发现了它。
不是说为整个应用只建立1个数据库连接吗?
如果我在文件 A 中执行 new Database() 并在文件 B 中执行 new Database(),仍然会有两个连接。
如果有帮助的话,我正在使用微型 MVC 框架。
class Database
{
private $pdo;
private $host;
private $databse;
private $username;
private $password;
public function __construct()
{
$this->host = Config::get('mysql/host');
$this->database = Config::get('mysql/database');
$this->username = Config::get('mysql/username');
$this->password = Config::get('mysql/password');
}
public function query($sql, $params)
{
$this->connect();
$sth = $this->pdo->prepare($sql);
$params = is_array($params) ? $params : [$params];
if ($sth->execute($params)) {
return $sth->fetch(PDO::FETCH_OBJ);
}
}
private function connect()
{
if (!$this->pdo) {
try {
$this->pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . ';charset=utf8', $this->username, $this->password);
} catch (Exception $e) {
die($e->getMessage());
}
}
}
}
【问题讨论】:
-
这个应该转移到codereview.stackexchange.com吗?
标签: php pdo lazy-loading