如何继承其他模型的模型在笨

问题描述:

我使用笨我的项目,我有这个类模式,我称之为创看起来像这样:如何继承其他模型的模型在笨

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://*.com/questions/46338/can-you -access-a-model-from-inside-another-model-in-codeigniter – steve

把文件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

你必须包括你的Human_model.php这样的Genesis_model:

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

或者你可以自动加载它在你的config/autoload.php文件,我认为是愚蠢=)

您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

核心/ 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

其他的解决办法

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

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