2011-07-04 52 views
9

我使用笨我的項目,我有這個類模式,我稱之爲創看起來像這樣:如何繼承其他模型的模型在笨

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

    function get() { 
     return 'human soul'; 
    } 
} 

和我有另一種模式,存儲在相同的目錄,其延伸Genesis_model

class Human_model extends Genesis_model { 
    function __construct() { 
     parent::__construct(); 
    } 

    function get_human() { 
     return $this->get(); 
    } 
} 

Human_model用於由人力控制器

class Human extends CI_Controller {  
    function __construct(){ 
     parent::__construct(); 
     $this->load->model('human_model'); 
    }  

    function get_human() { 
     $data['human'] = $this->human_model->get_human(); 
     $this->load->view('human/human_interface', $data); 
    } 
} 

如果我執行代碼,它會產生一個錯誤,指向返回$ this-> get()。它讀取「致命錯誤:Class'Genesis_model'在第2行的... \ application \ models \ human_model.php中未找到」。

我使用這種方法,因爲幾乎我所有的模型共享幾乎相同的結構。我收集了Genesis中的類似功能,而其他模型僅作爲它們所代表的表格的獨特數據供應商。它在我的asp.net(vb.net)中運行良好,但我不知道如何在codeigniter中執行此操作。

有沒有一種方法讓Human_model繼承Genesis_model。我不認爲我可以使用include('genesis_model.php')。我不知道它是否有效。

在此先感謝。

+0

有趣的答案在這裏http://stackoverflow.com/questions/46338/can-you -access-a-model-from-inside-another-model-in-codeigniter – steve

回答

7

把文件genesis_model.php核心目錄

+2

你的意思是讓它像MY_Controller一樣工作嗎? – dqiu

+0

是的。您可以根據需要爲模型創建儘可能多的擴展,只需將其放置在/ core /中,然後在方便時使用它們。 –

+0

我剛剛將genesis_model.php移動到/ core /,並將文件名和類名重命名爲MY_Controller.php和MY_Controller。 ,但執行停在Human_model中的$ this-> get()處,並顯示錯誤:「致命錯誤:調用未定義的方法Human_model :: get()in ..\程序\型號\ human_model.php」 我錯過了什麼 – dqiu

1

你必須包括你的Human_model.php這樣的Genesis_model:

include_once(APPPATH . 'folder/file' . EXT); 

或者你可以自動加載它在你的config/autoload.php文件,我認爲是愚蠢=)

4

您Human_model改成這樣:

include('genesis_model.php'); 
class Human_model extends Genesis_model { 
    function __construct() { 
     parent::__construct(); 
    } 

    function get_human() { 
     return parent::get(); 
    } 
} 

通知get_human功能和include

6

核心/ MY_Model是好的,如果有1只爲你的模型很重要超類。

如果您想從多於模型超類繼承,更好的選擇是更改自動加載配置。

在應用程序/配置/ autoload.php,加入這一行:

$autoload['model'] = array('genesis_model'); 
+2

我相信這個答案是完全這個問題的作者想要什麼,我已經有了一個MY_Model,並且想要擴展ME_Model中的MY_Model。通過將ME_Model放置在應用程序/模型中,並按照上面的建議自動加載,我可以實現這個目標。 –

+0

自動加載的目錄?我把我的第二個模型類放在覈心目錄中,並將類名稱放在自動載入中,錯誤提示找不到類。 – tingfungc

+0

@tingfungc這會在你的應用程序中加載任何可用的模型,通常在'application/models/'。 – Siphon

1

其他的解決辦法

<?php 
$obj = &get_instance(); 
$obj->load->model('parentModel'); 
class childModel extends parentModel{ 
    public function __construct(){ 
     parent::__construct(); 
    } 

    public function get(){ 
     return 'child'; 
    } 
} 
?>