我应该如何在PHP中的类中调用mysql数据库函数?

时间:2013-02-03 13:01:50

标签: php mysql static singleton database-connection

这是我一段时间以来一直在努力的事情,我知道我并不孤单。我正在寻找一种能够在我的PHP类中使用数据库连接的“最佳实践”方法。我刚刚开始阅读有关静态函数和单例的内容。我现在认为这是要走的路,但是如果你知道我的意思,我想避免在购买新锤之后将每个问题看作钉子。我知道我不是唯一一个对此进行查询的人,但我找不到一个很好的资源来解释它应该如何完成。

我认为我正在寻找的是一个可重复使用的类,可以删除或最小化任何全局调用。我知道出于性能原因,我不想制作类的多个副本或创建多个数据库实例。

我认为我所做的(我对某些词的定义有点模糊)是一个数据库单例。

我正在寻找的是一些建议。这是我“应该”使用数据库类的方式吗?如果是这样,我是以最好的方式写的吗?

这是PHP:

<?php
# set all errors and notices on.
error_reporting(E_ALL);
ini_set('display_errors', '1');


# database static class.
class database {

    private static $connection;
    private static $instance;

    private function __construct(){
        # run the connection here
        self::$connection='*dbcon*';
        echo 'connecting...<br />';
    }

    public static function getInstance(){
        # this only runs once, calling the construct once.
        if(!self::$instance){
            self::$instance = new database();
        }
        return self::$instance;     
    }

    private static function sanitise($data){
        # sanitise data before it's sent to the database
        return '~'.$data.'~';
        # sanitisation is flagged by adding tildas to a string.
    }

    public function runquery($query){
        echo 'running query...<br />';
        return self::$connection.' - '.self::sanitise($query);
    }
}

# user class
class myuser {

    function getuser($username){
        # this uses the database class, but shouldn't call a second copy of it.
        # I should be able to re-use the connection string created outside this class.
        # Doing so sould not trigger a reconnection (flagged by echoing 'connecting...')
        echo database::runquery('SELECT * FROM user_tbl WHERE username='.$username);
        # The above line will call everything I need to return a result including sanitisation.
    }
}

# this line would be needed to substantiate an instance of the database.
database::getInstance();
# run two queries on the database to see if they both run from the same connection
echo database::runquery('test query');
echo '<br />';
echo database::runquery('second test query');
echo '<br />';

# substantiate a new user class
$user = new myuser();
# load in the current user.
$user->getuser('mark');
?>

结果如下:

connecting...
running query...
*dbcon* - ~test query~
running query...
*dbcon* - ~second test query~
running query...
*dbcon* - ~SELECT * FROM user_tbl WHERE username=mark~

我的输出中只有一个“连接...”字符串,我可以从任何地方调用数据库查询,而无需在我所创建的每个类的构造函数中调用类似$this->database = new database();的内容。

0 个答案:

没有答案