2012-12-06 60 views
0

我使用CodeIgniter並已擴展CI_Model。所以我所有的車型現在延伸到MY_ModelCode 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); 

但如果我可以,我寧願自動化。

+1

這聽起來像你希望實現你的發展,這是在框架開發很常見的一個工廠模式。 – jsteinmann

+0

這個答案可以幫助你 - http://stackoverflow.com/a/8168711/540001 – beardedlinuxgeek

+0

@beardedlinuxgeek我不認爲路由器類實際上有這樣的模型的方法。 – Hailwood

回答

1

如果你稍微澄清一下情況,這可能會有所幫助。請多發一點你的代碼?

例如,情態動詞(CI中)通常被用作(幾乎)介紹如何使用「自::」單類,但它看起來像你想的產品爲對象。那麼,爲什麼在使用

self::$model 

代替

$this->model 

,你走樣產品模型讓我覺得你可能是故意這樣做的事實(這就是爲什麼我很困惑,爲什麼你會這麼做嗎?)。我認爲你應該回顧「self ::」,「static ::」和「$ this->」之間的區別看看http://php.net/manual/en/language.oop5.late-static-bindings.php

rockstarz是正確的,你需要使用工廠模式。考慮這樣的事情:

class ItemFactory { 

    private $model; 

    public function __construct($model) { 
     $this->model = $model; 
    } 

    function create_product(stdClass $data) { 
     $product = new Product($data); 
     $product->set_model($this->model); 
     return $product 
    } 
} 

abstract class Item { 

    protected $model; 
    protected $ci = & get_instance(); 

    public function __construct(stdClass $data) { 
     // whatever 
    } 

    public function set_model($model) { 
     $this->$model = $model; 
    } 

    public function get_model() { 
     return $this->model; 
    } 

} 

class Product extends Item { 
    // whatever 
} 

那麼你的模型可以只使用它像

class Product_Model extends MY_Model { 

    private $item_factory; 

    public function __construct() { 
     $this->item_factory = new ItemFactory($this); 
    } 

    public function get($id){ 
     return $this->item_factory->create_product($row); 
    } 

} 

相關閱讀材料:

http://en.wikipedia.org/wiki/Inversion_of_control#Implementation_techniques

http://en.wikipedia.org/wiki/Factory_method_pattern

http://en.wikipedia.org/wiki/Dependency_injection

+0

是啊,我應該提到的是,我存儲'$ ci'和'$ model'靜態成員的原因是因爲我不想讓他們在我的調試打印出來基本上'var_dump'和'print_r'排除靜態成員。 – Hailwood

相關問題