我有一个PDO
对象连接到数据库,我有5个类需要数据库连接的方法。对于我正在构建$db
的每个班级。这是真的方法吗?如果没有,我该怎么办?
try {
$config['db'] = array(
'host' => 'localhost',
'username' => 'xxxxxx',
'password' => 'xxxxxx',
'dbname' => 'table_name'
);
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
} catch (Exception $e) {
echo "!";
}
//classA
class ClassA{
private $db;
public function __construct(PDO $db){
$this->db = $db;
}
public function methodA1($someId){
$res = $this->db->query("SELECT * FROM bla WHERE id = $someId ");
return $res->fetchAll(PDO::FETCH_ASSOC);
}
}
//classB
class ClassB{
private $db;
public function __construct(PDO $db){
$this->db = $db;
}
public function methodB1($someId){
$res = $this->db->query("SELECT * FROM bla WHERE id = $someId ");
return $res->fetchAll(PDO::FETCH_ASSOC);
}
}
然后我为这些类创建新对象,如
$classAObject = new ClassA($db);
$classBObject = new ClassB($db);
在创建对象时,我是否连接过DB 2次?
答案 0 :(得分:1)
它连接一次。
您正在使用相同的PDO对象,因此它只会使用您在包含文件时初始化的对象。
我建议你把它变成一个单例,这样当你使用PDO对象时,你总是得到一个已被初始化的对象,将被所有连接使用。
模型类
class Model {
private $_mysql;
public function __construct() {
//Get "singleton" instance of the DatabaseConnector (shared between all Models)
$this->_mysql = DatabaseConnector::getInstance();
}
}
DatabaseConnector类
class DatabaseConnector extends Singleton {
private $_mysql;
public function __construct() {
$this->_mysql = new PDO(...);
}
public function beginTransaction() {
return $this->_mysql->beginTransaction();
}
public function commit() {
return $this->_mysql->commit();
}
public function rollback() {
return $this->_mysql->rollback();
}
}
Singleton类
class Singleton
{
/**
* @var Singleton The reference to *Singleton* instance of this class
*/
private static $instance;
/**
* Returns the *Singleton* instance of this class.
*
* @return Singleton The *Singleton* instance.
*/
public static function getInstance()
{
if (null === static::$instance) {
static::$instance = new static();
}
return static::$instance;
}
/**
* Protected constructor to prevent creating a new instance of the
* *Singleton* via the `new` operator from outside of this class.
*/
protected function __construct(){}
/**
* Private clone method to prevent cloning of the instance of the
* *Singleton* instance.
*
* @return void
*/
private function __clone(){}
/**
* Private unserialize method to prevent unserializing of the *Singleton*
* instance.
*
* @return void
*/
private function __wakeup(){}
}
您可以查看此详细信息singleton
此外,您最好将文件分开,在一个文件中只有一个单独的类。
答案 1 :(得分:0)
如果你传递每个对象对同一个$db
对象的引用,你所做的就是初始化对象的属性,PDO $db
等于传递的PDO对象,所以不,我不要相信你会不止一次连接到数据库。