你有沒有考慮通過名稱作爲參數傳遞給fetchAll()
方法?
class Email extends Model
{
protected $_name = 'zEmailz';
public function getResults()
{
$rows = parent::fetchAll($this->$_name);
}
}
我不建議設置Model::$_name
靜態,因爲任何可能的重複可以覆蓋該值,使其難以確保你想要的電流值相匹配。這是混合靜態和實例化成員的許多缺陷之一。
- 更新 -
您可以將對象傳遞到fetchAll
通話,排序的(說有點二/三我從來沒有共同混合DI與靜態調用)的依賴注射液:
// Calling code
$email = new Email();
// Do stuff with $email
$results = Model::fetchAll($email);
那麼模型類的樣子:
abstract class Model
{
public static function fetchAll($object)
{
$request = new ApiRequest();
return $request->get($object->_name);
}
}
- 更新#2 -
根據您的評論,您正在尋找一種方法從數據庫中檢索行併爲主對象提供水合物,以便您可以通過OO API調用引用當前值。如果我是你,你會看看Doctrine,而不是重新發明輪子。在學說中,他們擁有所謂的「表格」類,它們與模型類直接相關。例如,您將擁有一個EmailTable.php
文件,並且在此類中您將添加自定義方法以返回所需的數據集。
如果你仍然想堅持自己這樣做的方式,那麼你可能要到fetchAll
方法進入各子類,否則,如果你把它在父類,你會與一個討厭落得開關/外殼塊,用於你想要水合的所有物體。
例(示範只):
class Email extends Model
{
protected $_name = 'zEmailz';
public static function fetchAll()
{
// However you pull rows from DB
while ($row = get_current_row) {
$email = new Email();
$email->setAddress($row['address']);
...
$emails[] = $email;
}
return $emails;
}
}
基於他肯定想要遲到靜態綁定的問題。 –