2011-10-12 48 views
1

我試圖在codeigniter中構造我的函數來保持事物的頂部。基本上我可以這樣做:Codeigniter中的結構函數

$this->my_model->get_everything(); 
$this->my_model_db->write_all(); 

但當然,我最終制作和加載許多文件。我寧願像我的JS代碼那樣構造它,並擴展我的模型:

$this->my_model->db->write_all(); 

這對我來說是最合理和最可讀的解決方案。我嘗試過,但對於PHP對象和類(還沒有),我不太好。有沒有簡單的方法來實現這一點?還是有更實際的解決方案?謝謝!

回答

4

我認爲你是在倒退。

您可以使用所需的常規功能創建多個模型,以擴展內置的CI_Model類。然後,您可以從這些新類繼承特定的實現。

例如,假設你有一個數據庫表名賬戶工作

首先,創建可擴展CI_Model包含一般功能與一組數據的工作(CI_DB_Result,數組類模型,數組陣列等)。喜歡的東西:

abstract class table_model extends CI_Model 
{ 
    function __construct() 
    { 
    parent::__construct(); 
    } 

    public function write_all() 
    { 
    // do some stuff to save a set of data 
    // maybe add some logging in here too, if it's on development 
    // and how about some benchmarking for performance testing too 
    // you get the idea 
    } 
} 

接下來,創建可擴展table_model一類,但具體到帳戶表函數。

public class accounts_model extends table_model 
{ 
    function __construct() 
    { 
    parent::__construct(); 
    } 

    public function get_everything() 
    { 
    // whatever it takes to get everything... 
    } 
} 

最後,你可以做的東西一樣......

$this->account_model->get_everything(); 
$this->account_model->write_all(); 

如果你有另一種模式(my_model),您也可以這樣做:

$this->my_model->get_just_a_few_things(); 
$this->my_model->write_all();