PHP - 数据库抽象层使用静态类与单例对象?
我不想创建一个关于单例的讨论,而不是静态的,或者比全局更好,等等。我读了几十个关于SO类似主题的问题,但我无法想出这个特定问题的答案,所以我希望现在有人可以用一个(或多个)真实简单的例子来回答这个问题,而不仅仅是理论讨论来阐明我。
在我的应用程序中,我有典型的数据库类来抽象数据库层并在数据库上执行任务,而无需在代码中到处编写mysql_connect / mysql_select_db / mysql...
我可以将类编写为静态类:
class DB
{
private static $connection = FALSE; //connection to be opened
//DB connection values
private static $server = NULL; private static $usr = NULL; private static $psw = NULL; private static $name = NULL;
public static function init($db_server, $db_usr, $db_psw, $db_name)
{
//simply stores connections values, without opening connection
}
public static function query($query_string)
{
//performs query over alerady opened connection, if not open, it opens connection 1st
}
...
}
或作为单例:
class DBSingleton
{
private $inst = NULL;
private $connection = FALSE; //connection to be opened
//DB connection values
private $server = NULL; private $usr = NULL; private $psw = NULL; private $name = NULL;
public static function getInstance($db_server, $db_usr, $db_psw, $db_name)
{
//simply stores connections values, without opening connection
if($inst === NULL)
$this->inst = new DBSingleton();
return $this->inst;
}
private __construct()...
public function query($query_string)
{
//performs query over already opened connection, if connection is not open, it opens connection 1st
}
...
}
然后在我的应用程序中,如果我想查询我可以做的数据库
//Performing query using static DB object
DB:init(HOST, USR, PSW, DB_NAME);
DB::query("SELECT...");
//Performing query using DB singleton
$temp = DBSingleton::getInstance(HOST, USR, PSW, DB_NAME);
$temp->query("SELECT...");
对我来说,Singleton的唯一优点是避免声明为类的每个方法。我相信你们中的一些人可以给我一个示例,说明在这种特定情况下单例的真正优势。提前致谢。static