問題描述
我希望能夠創建擴展 MySQLi 類以執行其所有 SQL 查詢的類.
I want to be able to make classes which extend the MySQLi class to perform all its SQL queries.
$mysql = new mysqli('localhost', 'root', 'password', 'database') or die('error connecting to the database');
如果不將 $mysql 對象全球化以在我的其他方法或類中使用,我不知道如何做到這一點.
I dont know how to do this without globalising the $mysql object to use in my other methods or classes.
class Blog {
public function comment() {
global $mysql;
//rest here
}
}
任何幫助將不勝感激.
謝謝.
推薦答案
我的建議是創建一個 Singleton DataAccess 類,在全局配置文件中實例化該類并在您的 Blog 類中調用它,例如 $query = DataAccess::query("SELECT * FROM blog WHERE id = ".$id)
.
My suggestion is to create a Singleton DataAccess class, instantiate that class in a global config file and call it in your Blog class like $query = DataAccess::query("SELECT * FROM blog WHERE id = ".$id)
.
看看單例模式,這是一個非常容易理解的設計模式.非常適合這種情況.
Look into the Singleton pattern, it's a pretty easy to understand designpattern. Perfect for this situation.
您的 DataAccess 類可以有多種方法,例如 query
、fetchAssoc
、numRows
、checkUniqueValue
、transactionStart
、transactionCommit
、transactionRollback
等.這些函數也可以設置為由 DataAccess 類實現的接口.這樣您就可以輕松地為多個數據庫管理系統擴展您的 DataAccess 類.
Your DataAccess class can have several methods like query
, fetchAssoc
, numRows
, checkUniqueValue
, transactionStart
, transactionCommit
, transactionRollback
etc etc. Those function could also be setup as an Interface which gets implemented by the DataAccess class. That way you can easily extend your DataAccess class for multiple database management systems.
以上幾乎描述了我的 DataAccess 模型.
The above pretty much describes my DataAccess model.
這篇關于擴展 MySQLi 類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!