我將使用單例類來管理數據庫連接和對應用程序設置的引用。OO PHP哪裏可以參考singleton類?
爲了訪問db類,必須在每個方法中使用下面的代碼似乎有點麻煩。
$db = DB::getInstance();
是否有更有效的方法去實現它?
任何意見讚賞。
謝謝
我將使用單例類來管理數據庫連接和對應用程序設置的引用。OO PHP哪裏可以參考singleton類?
爲了訪問db類,必須在每個方法中使用下面的代碼似乎有點麻煩。
$db = DB::getInstance();
是否有更有效的方法去實現它?
任何意見讚賞。
謝謝
我經常使用的註冊模式,其中發生這種情況時也是如此。我總是在我的模型的構造函數中設置一個實例變量來指向註冊表項;
class Registry {
private static $_instance;
private $_registry;
private function __construct() {
$_registry = array();
}
public static function getInstance() {
if (!Registry::$_instance) {
Registry::$_instance = new Registry();
}
return Registry::$_instance;
}
public function add($key, &$entry) {
$this->_registry[$key] = &$entry;
}
public function &get($key) {
return $this->_registry[$key];
}
public function has($key) {
return ($this->get($key) !== null);
}
}
模型示例;
class MyModel {
private $_db;
public function __construct() {
$this->_db = Registry::getInstance()->get('dbKey');
}
/* Every function has now access to the DAL */
}
實例化示例;
$dal = new Db(...);
Registry::getInstance()->add('dbKey', $dal);
...
$model = new MyModel();
$model->doDbStuff();
另一種方法是始終將引用作爲參數傳遞給每個構造函數。
當然,我只在我的模型中的大多數方法使用引用時才使用這種行爲,如果只有少數(一兩個)方法使用引用,我就像你所展示的那樣調用Registry/Singleton。
這不是混亂。這是單身人士的預期行爲。而且,實際上,這只是一行代碼。你想讓它更緊湊嗎? :)
我的首選方法是創建一個基類,所有需要db訪問的類下降。 Base在其構造函數中調用單例。所有的孩子都會調用他們的父構造函數。例如: -
class Base {
protected $db;
public function __construct(){
$this->db = DB::getInstance();
}
}
class Achild extends Base {
protected $var1;
public function __construct($arg){
parent::__construct();
$this->var1=$arg;
}
}
我知道你的意思......討厭:: getInstance()的東西!所以,去用靜態方法:
class DB {
private static $db;
public static function getInstance() {
if(!self::$db) {
self::$db = new DBconnector();
}
}
public static function query($query) {
return self::$db->query($query);
}
}
用法是好得多:
$result = DB::query('SELECT whatever;');
如果你使用PHP 5.3,你可以寫一個__callStatic與此類似,轉發所有方法調用的對象:
public static function __callStatic($method, $args) {
call_user_func_array(array(self::$db, $method), $args);
}
爲了讓我開心,請添加一個__autoloader,以便您可以隨時訪問數據庫而無需擔心!
我只是不想在每一個需要它的方法開始時重複這一行。 我曾考慮將其添加到構造函數中,但不確定這是否被認爲是良好的實踐。 – Dan 2009-10-30 12:28:15
添加到構造函數中的「風險」是,當你不需要它時,你也可以得到Singleton - 在某些情況下可能會不方便。如果這個類很聰明,那麼當沒有查詢時它不會啓動數據庫連接,但如果沒有,則會產生開銷。 – smint 2009-10-30 12:38:55