【发布时间】:2014-01-28 21:06:04
【问题描述】:
我一直在尝试使用 PDO 和单例创建数据库连接。我想我已经完成了,但我不确定我是否使用了正确的单例模式。
我也不确定我是否正确使用了__clone() 和__wakeup() 方法。而且我没有测试它们的知识。
谁能告诉我我的方法是否正确以及我是否正确使用了单例模式?我对设计模式很陌生。
这是我的代码:
<?php
require_once 'config.php';
class dbConn{
// Variable to store connection object.
protected static $db;
// Assign variables from config.php.
private $host = DB_HOST;
private $dbuser = DB_USER;
private $dbpass = DB_PASS;
private $dbname = DB_NAME;
// Private construct - class cannot be instatiated externally.
private function __construct() {
try {
// Try to create PDO object to the $db variable.
$pre = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
self::$db = new PDO($pre, $this->dbuser, $this->dbpass);
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
// If not able to connect to database.
catch (PDOException $e) {
echo "Could not connect: " . $e->getMessage();
}
}
// Get connection function.
public static function getConnection() {
// Only if no connection object exists it creates one, because we only want one instance.
if (!self::$db) {
// New connection object.
new dbConn();
}
return self::$db;
}
public function __clone() {
return false;
}
public function __wakeup(){
return false;
}
}
$db = dbConn::getConnection()
?>
【问题讨论】:
标签: php design-patterns pdo singleton