我使用CodeIgniter並已擴展CI_Model
。所以我所有的車型現在延伸到MY_Model
。Code Igniter獲取創建對象的模型實例的名稱?
這工作正常。
問題是我所有的模型都有一個輔助關聯對象。基本上是一個從模型傳遞數據的類(通常來自數據庫),並表示數據庫中的那一行。
所以像
class Product_Model extends MY_Model{
public function get($id){
//....
return new Product($query->row());
}
}
class Product{
public function __construct(stdClass $data){
//....
self::$ci =& get_instance();
self::$model = self::$ci->products;
}
}
現在我加載Product_Model與因此具有self::$model = self::$ci->products;
別名$this->load->model('product_model', 'products');
但現在我想有一個基本類,所有的類,如Product
會延伸。我想要這個包含邏輯更新self::$model
。
但我需要知道模型別名。
喜歡的東西
self::$model = self::$ci->{instantiator_variable_name($this)}
這將是self::$model = self::$ci->products
現在很明顯的是功能不存在,但它顯示了我想做的事情。
我知道我可以到處爲我創造Product
或類似的有
$row = $query->row();
$row->model = $this->ci->products;
return new Product($row);
但如果我可以,我寧願自動化。
這聽起來像你希望實現你的發展,這是在框架開發很常見的一個工廠模式。 – jsteinmann
這個答案可以幫助你 - http://stackoverflow.com/a/8168711/540001 – beardedlinuxgeek
@beardedlinuxgeek我不認爲路由器類實際上有這樣的模型的方法。 – Hailwood