这是我已经挣扎了一段时间的事情,我知道我并不孤单。我正在寻找一种能够在我的 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();
在我创建的每个类的构造函数中调用类似的东西。