[英]php Use class function that queries db inside another class
我設置了多個類,它們都需要訪問數據庫,而它們確實需要這樣做。 當我想使用另一類中的一個函數時,麻煩就來了。
class General
{
private $_db = NULL;
private $_db_one;
private $_db_two;
private $offset;
public function __construct ( PDO $db ) {
$this->_db = $db;
$this->_db_one = 'lightsnh_mage1';
$this->_db_two = 'lightsnh_inventory';
$this->offset = 10800;
}
public function getTableNames() {
$sql = 'SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = "BASE TABLE" AND TABLE_SCHEMA="' . $this->_db_two . '"';
$statement = $this->_db->query($sql);
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
這可以正常工作,然后我的其他課程也以相同的方式連接。 正如您將在下面的“ Distributors”類中看到的那樣,我在構造函數中實例化了“ General”類。 當我在寫作時學習時,我不禁感到有一種更加通用的方式或有效的連接方式。
class Distributors
{
private $_db = NULL;
private $_db_one;
private $_db_two;
private $_source_tbl;
public $lights;
public function __construct ( PDO $db ) {
$this->_db = $db;
$this->_db_one = 'lightsnh_mage1';
$this->_db_two = 'lightsnh_inventory';
$this->_source_tbl = 'distributors';
// is this the best way to get functions from another class inside of this class? I have 10 classes I will need to repeat this for.
$this->lights = new General($db);
}
public function getInventorySources() {
// calling function from General class inside my distributor class
$tables = $this->lights->getTableNames();
// using result of General function inside of a function from Distributors class
$sql = 'SELECT * FROM `' . $tables . '` WHERE `exclude` = 0';
$statement = $this->_db->query($sql);
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
Singleton
只是全球狀態的另一種形式,這很糟糕。 您應該始終避免它。
從您的代碼示例中,
public function __construct ( PDO $db ) {
$this->_db = $db;
$this->_db_one = 'lightsnh_mage1';
$this->_db_two = 'lightsnh_inventory';
$this->_source_tbl = 'distributors';
// is this the best way to get functions from another class inside of this class? I have 10 classes I will need to repeat this for.
$this->lights = new General($db);
}
當您以這種方式實例化時, $this->lights = new General($db);
您可以從全球范圍內選擇普通班。 因此,幾乎不可能進行模擬和單元測試。
相反,應該像對PDO
一樣注入General
實例。 像這樣:
public function __construct (PDO $db, General $general)
{
$this->_db = $db;
$this->_db_one = 'lightsnh_mage1';
$this->_db_two = 'lightsnh_inventory';
$this->_source_tbl = 'distributors';
// is this the best way to get functions from another class inside of this class? I have 10 classes I will need to repeat this for.
$this->lights = $general;
}
您將以這種方式使用它:
$pdo = new PDO(...);
$pdo->setAttribute(...);
$general = new General($pdo);
$distributors = new Distributors($pdo, $general);
這是從該類中另一個類獲取函數的最佳方法嗎? 我有10個課程,需要重復進行。
是的,您應該重復該操作,而不是實例化,而是依賴項注入。 這使您的代碼更具可維護性,並且不會引入全局狀態。
除此之外,您的General
班級顯然違反了單一責任原則 。
我不知道您會遇到什么問題,但我認為getTableNames函數將返回對象或數組,因此$tables
的結果不是字符串,則執行var_dump($tables);
看看$tables
什么
嘗試用谷歌搜索出路。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.