简体   繁体   English

More Than 1 __construct($db) 会尝试连接多个数据库吗?

[英]Will More Than 1 __construct($db) try to connect to DB more than one?

I have a PDO object which connect to database and I have 5 classes which requires database connection for their methods.我有一个连接到数据库的PDO对象,我有 5 个类,它们的方法需要数据库连接。 For every class I'm constructing a $db .对于每个类,我都在构建一个$db Is it true approach?这是真正的方法吗? If not, what should I do?如果没有,我该怎么办?

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);
    }
}

Then I crate new objects for these classes like然后我为这些类创建新对象,例如

$classAObject = new ClassA($db);
$classBObject = new ClassB($db);

While I creating my object, Am I connecting to DB 2 times?在创建对象时,我是否连接到 DB 2 次?

It connects once.它连接一次。

You are using the same PDO object so it will just use the object you initialize when you include the file.您正在使用相同的 PDO 对象,因此它只会使用您在包含文件时初始化的对象。

I suggest you make it a singleton so when you are using the PDO object you always get the object that has been initialized which would be used by all connections.我建议你让它成为一个单例,这样当你使用 PDO 对象时,你总是得到已经初始化的对象,它将被所有连接使用。

Model class模型类

class Model {
    private $_mysql;

    public function __construct() {
        //Get "singleton" instance of the DatabaseConnector (shared between all Models)
        $this->_mysql = DatabaseConnector::getInstance();
    }
}

DatabaseConnector class数据库连接器类

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单例类

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(){}

}

You can check this for more detail singleton您可以查看此以获取更多详细信息单例

Besides, you'd better separate your files to have only one single class in one file.此外,您最好将文件分开,以便在一个文件中只有一个类。

如果你给每个对象传递一个对同一个$db对象的引用,你所做的就是初始化对象的属性, PDO $db等于传递的 PDO 对象,所以不,我不相信你会连接到数据库不止一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将多个值存储到db字段中,以作为单独的值检索 - store more than one value into a db field to be retrieved as separate values 您可以在一个数据库连接上使用 mysqli->prepare 使用多个查询吗? - Can you use more than one query with mysqli->prepare on one db connection? 如果结果不止一个,则对db中一个字段的值进行排名,并仅返回最高/最低排名值 - If more than one result, rank values from one field in db and return only the highest/lowest ranked value 如何使用Zend_Db添加多行? - How do I add more than one row with Zend_Db? 从数据库中获取多个记录时,mysql子查询返回错误 - Mysql subquery return error when more than one record is fetched from db 当用户有多个与我想要的结果相关的表时,如何查询数据库? - how to query db when user has more than one table associated with the results i want? 如何在表(MySQL DB)中为一行存储大量数据(超过3000行)? - How to store a lot of data (more than 3000 rows) for one row in a table (MySQL DB)? Eloquent:获取列值(x)存在于多于一行的所有行(SQL DB) - Eloquent: Get all rows where column value(x) exists in more than one row (SQL DB) 一个以上的重写器 - More than one rewriterule 如果数据库中存在多个输出,则不会显示输出 - Output won't display if it exists more than once in the DB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM