MySQL数据库配置在一个单独的类中

时间:2021-05-28 16:25:25

Is it possible to keep all my database related configuration (hostnames, usernames, passwords, and databases) as well as the function to connect to and select the correct database in a separate class?

是否可以保留所有与数据库相关的配置(主机名,用户名,密码和数据库)以及连接到并在单独的类中选择正确数据库的功能?

I tried something like this:

我试过这样的事情:

class Database
{
    var $config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );
    function __construct() {
        $this->connect();
    }
    function connect() {
        $db = $this->config;
        $conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
        if(!$conn) {
            die("Cannot connect to database server"); 
        }
        if(!mysql_select_db($db['database'])) {
            die("Cannot select database");
        }
    }
}

And then in another class I would use in the classes __construct function:

然后在另一个类中我会在类__construct函数中使用:

require_once('database.php');
var $db_conn = new Database();

But this doesnt save the connection, it ends up defaulting to the servers local db connection. Or do I have to do the database commands everytime before I execute some database commands?

但这并没有保存连接,它最终默认为服务器本地数据库连接。或者,在执行某些数据库命令之前,每次都必须执行数据库命令?

4 个解决方案

#1


7  

I modified your class to work as you seem to be expecting it to:

我修改了你的课程,因为你似乎期望它:

<?php
class Database
{
    var $conn = null;
    var $config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );

    function __construct() {
        $this->connect();
    }

    function connect() {
        if (is_null($this->conn)) {
            $db = $this->config;
            $this->conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
            if(!$this->conn) {
                die("Cannot connect to database server"); 
            }
            if(!mysql_select_db($db['database'])) {
                die("Cannot select database");
            }
        }
        return $this->conn;
    }
}

Usage:

用法:

$db = new Database();
$conn = $db->connect();

Note that you can call connect() as many times as you like and it will use the current connection, or create one if it doesn't exist. This is a good thing.

请注意,您可以根据需要多次调用connect(),它将使用当前连接,或者如果它不存在则创建一个连接。这是件好事。

Also, note that each time you instantiate a Database object (using new) you will be creating a new connection to the database. I suggest you look into implementing your Database class as a Singleton or storing it in a Registry for global access.

另请注意,每次实例化Database对象(使用new)时,您都将创建与数据库的新连接。我建议您考虑将Database类实现为Singleton或将其存储在Registry中以进行全局访问。

You can also do it the dirty way and shove it in $GLOBALS.

你也可以用脏的方式把它推到$ GLOBALS。

Edit

编辑

I took the liberty of modifying your class to implement the Singleton pattern, and follow the PHP5 OOP conventions.

我冒昧地修改你的类来实现Singleton模式,并遵循PHP5 OOP约定。

<?php
class Database
{
    protected static $_instance = null;

    protected $_conn = null;

    protected $_config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );

    protected function __construct() {
    }

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function getConnection() {
        if (is_null($this->_conn)) {
            $db = $this->_config;
            $this->_conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
            if(!$this->_conn) {
                die("Cannot connect to database server"); 
            }
            if(!mysql_select_db($db['database'])) {
                die("Cannot select database");
            }
        }
        return $this->_conn;
    }

    public function query($query) {
        $conn = $this->getConnection();
        return mysql_query($query, $conn);
    }
}

Usage:

用法:

$res = Database::getInstance()->query("SELECT * FROM foo;");

or

要么

$db = Database::getInstance();
$db->query("UPDATE foo");
$db->query("DELETE FROM foo");

#2


0  

You can certainly keep your connection info in a separate file.

您当然可以将您的连接信息保存在单独的文件中。

Just save your connection object - $conn in your connect() function - in a class variable. You'll then be able to reuse it across calls.

只需在connect()函数中保存连接对象 - $ conn - 在类变量中。然后,您就可以在呼叫中重复使用它。

#3


0  

In your method connect() $conn is only a local variable that only exists in the scope of that method. As soon as the method returns there will be no (other) reference to the connection resource and it will be collected/disposed. You'll need at least

在你的方法中,connect()$ conn只是一个只存在于该方法范围内的局部变量。一旦该方法返回,就不会有(其他)对连接资源的引用,它将被收集/处理。你至少需要

$this->conn = mysql_connect(...)

#4


0  

Here comes the singleton with PDO example. Thanks to @hodobave

这是带有PDO示例的单例。感谢@hodobave

<?php 

/**
 * DB Connection class
 * Singleton pattern
 * An single instance of DB connection is created
**/

class Db{

    protected static $_instance = null;
    protected $_conn;

    protected $_config = [
        'username' => 'root',
        'password' => '',
        'hostname' => 'localhost',
        'database' => 'news',
    ];
    protected function __construct(){

    }

    public function getInstance(){
        if(null === self::$_instance){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function getConnection(){
        if(is_null($this->_conn)){
            //connect here
            $db = $this->_config;
            $dsn = "mysql:host={$db['hostname']};dbname={$db['database']}";
            $this->_conn = new PDO($dsn, $db['username'], $db['password']);
        }
        return $this->_conn;
    }

    public function query($sql){
        $args = func_get_args();
        array_shift($args);
        $statement = $this->getConnection()->prepare($sql);
        $statement->execute($args);
        return $statement->fetchAll(PDO::FETCH_OBJ);
    }
}



$res = Db::getInstance();
$users = $res->query("SELECT * FROM `user` WHERE id=?",1);
print_r($users);
?> 

#1


7  

I modified your class to work as you seem to be expecting it to:

我修改了你的课程,因为你似乎期望它:

<?php
class Database
{
    var $conn = null;
    var $config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );

    function __construct() {
        $this->connect();
    }

    function connect() {
        if (is_null($this->conn)) {
            $db = $this->config;
            $this->conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
            if(!$this->conn) {
                die("Cannot connect to database server"); 
            }
            if(!mysql_select_db($db['database'])) {
                die("Cannot select database");
            }
        }
        return $this->conn;
    }
}

Usage:

用法:

$db = new Database();
$conn = $db->connect();

Note that you can call connect() as many times as you like and it will use the current connection, or create one if it doesn't exist. This is a good thing.

请注意,您可以根据需要多次调用connect(),它将使用当前连接,或者如果它不存在则创建一个连接。这是件好事。

Also, note that each time you instantiate a Database object (using new) you will be creating a new connection to the database. I suggest you look into implementing your Database class as a Singleton or storing it in a Registry for global access.

另请注意,每次实例化Database对象(使用new)时,您都将创建与数据库的新连接。我建议您考虑将Database类实现为Singleton或将其存储在Registry中以进行全局访问。

You can also do it the dirty way and shove it in $GLOBALS.

你也可以用脏的方式把它推到$ GLOBALS。

Edit

编辑

I took the liberty of modifying your class to implement the Singleton pattern, and follow the PHP5 OOP conventions.

我冒昧地修改你的类来实现Singleton模式,并遵循PHP5 OOP约定。

<?php
class Database
{
    protected static $_instance = null;

    protected $_conn = null;

    protected $_config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );

    protected function __construct() {
    }

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function getConnection() {
        if (is_null($this->_conn)) {
            $db = $this->_config;
            $this->_conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
            if(!$this->_conn) {
                die("Cannot connect to database server"); 
            }
            if(!mysql_select_db($db['database'])) {
                die("Cannot select database");
            }
        }
        return $this->_conn;
    }

    public function query($query) {
        $conn = $this->getConnection();
        return mysql_query($query, $conn);
    }
}

Usage:

用法:

$res = Database::getInstance()->query("SELECT * FROM foo;");

or

要么

$db = Database::getInstance();
$db->query("UPDATE foo");
$db->query("DELETE FROM foo");

#2


0  

You can certainly keep your connection info in a separate file.

您当然可以将您的连接信息保存在单独的文件中。

Just save your connection object - $conn in your connect() function - in a class variable. You'll then be able to reuse it across calls.

只需在connect()函数中保存连接对象 - $ conn - 在类变量中。然后,您就可以在呼叫中重复使用它。

#3


0  

In your method connect() $conn is only a local variable that only exists in the scope of that method. As soon as the method returns there will be no (other) reference to the connection resource and it will be collected/disposed. You'll need at least

在你的方法中,connect()$ conn只是一个只存在于该方法范围内的局部变量。一旦该方法返回,就不会有(其他)对连接资源的引用,它将被收集/处理。你至少需要

$this->conn = mysql_connect(...)

#4


0  

Here comes the singleton with PDO example. Thanks to @hodobave

这是带有PDO示例的单例。感谢@hodobave

<?php 

/**
 * DB Connection class
 * Singleton pattern
 * An single instance of DB connection is created
**/

class Db{

    protected static $_instance = null;
    protected $_conn;

    protected $_config = [
        'username' => 'root',
        'password' => '',
        'hostname' => 'localhost',
        'database' => 'news',
    ];
    protected function __construct(){

    }

    public function getInstance(){
        if(null === self::$_instance){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function getConnection(){
        if(is_null($this->_conn)){
            //connect here
            $db = $this->_config;
            $dsn = "mysql:host={$db['hostname']};dbname={$db['database']}";
            $this->_conn = new PDO($dsn, $db['username'], $db['password']);
        }
        return $this->_conn;
    }

    public function query($sql){
        $args = func_get_args();
        array_shift($args);
        $statement = $this->getConnection()->prepare($sql);
        $statement->execute($args);
        return $statement->fetchAll(PDO::FETCH_OBJ);
    }
}



$res = Db::getInstance();
$users = $res->query("SELECT * FROM `user` WHERE id=?",1);
print_r($users);
?>