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

发布于 2024-07-30 01:53:07 字数 912 浏览 3 评论 0原文

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

我尝试了这样的方法:

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

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

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

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

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:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

栀子花开つ 2024-08-06 01:53:07

我修改了您的类,使其按照您似乎期望的方式工作:

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

用法:

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

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

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

您也可以采用肮脏的方式将其放入 $GLOBALS 中。

编辑

我擅自修改了您的类以实现单例模式,并遵循 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);
    }
}

用法:

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

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

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.

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.

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

Edit

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

<?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");
狼性发作 2024-08-06 01:53:07

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

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

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.

执手闯天涯 2024-08-06 01:53:07

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

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

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

$this->conn = mysql_connect(...)
药祭#氼 2024-08-06 01:53:07

这是带有 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);
?> 

Here comes the singleton with PDO example. Thanks to @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);
?> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文