我正在开发一个新项目。在这个项目中,我使用了我第一次使用的pdo单例类,我不知道我是否做得对。
如果你能给我提示或改进,那就太好了。
<?php
namespace App\Libraries;
class Database
{
private $_config;
private $_instance = null;
public function __construct($config)
{
$this->_config = $config;
}
public function getInstance()
{
if ($this->_instance == null) {
try {
$this->_instance = new \PDO('mysql:host=' . $this->_config['database']['host'] . ';dbname=' . $this->_config['database']['name'] . ';charset=' . $this->_config['database']['charset'], $this->_config['database']['username'], $this->_config['database']['password'], [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
} catch (PDOException $e) {
die($e->getMessage());
}
}
return $this->_instance;
}
public function __destruct()
{
$this->_config = null;
$this->_instance = null;
}
}
?>
$config
变量只是我的配置文件,我按如下方式使用了该类:
$db = new Database($config);
$db->getInstance()->query(...);
干杯, 很少
答案 0 :(得分:0)
Database
不是单例,因为您可以创建此类的多个实例。如果需要单例,请对save实例使用static属性。并删除构造函数(将其声明为私有)。
<?php
namespace App\Libraries;
class Database
{
private static $_instance = null;
private function __construct()
{
}
public static function getInstance()
{
$config = // Implement reading of configuration
if ($this::$_instance == null) {
try {
$this::$_instance = new \PDO('mysql:host=' . $config['database']['host']
. ';dbname=' . $config['database']['name']
. ';charset=' . $config['database']['charset'],
$config['database']['username'],
$config['database']['password'], [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
} catch (PDOException $e) {
die($e->getMessage());
}
}
return $this::$_instance;
}
}
?>
你会像这样使用Database
:
$db = Database::getInstance()->query(...);