12

我正在为我的项目使用 codeigniter,我有这个类模型,我称之为 Genesis,它看起来像这样:

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 由 Human 控制器使用

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()。它显示“致命错误:在第 2 行的 ...\application\models\human_model.php 中找不到类 'Genesis_model'”。

我使用这种方法是因为我几乎所有的模型都具有几乎相同的结构。我在 Genesis 中收集了类似的功能,而其他模型仅作为它们所代表的表所独有的数据提供者。它在我的asp.net(vb.net)中运行良好,但我不知道如何在codeigniter中做到这一点。

Human_model 有没有办法继承 Genesis_model。我不认为我可以使用include('genesis_model.php')。我也不知道它是否有效。

提前致谢。

4

5 回答 5

8

如果您的模型只有 1 个重要的超类,那么 core/MY_Model 很好。

如果您想继承的不仅仅是模型超类,更好的选择是更改您的自动加载配置。

在 application/config/autoload.php 中,添加这一行:

    $autoload['model'] = array('genesis_model');
于 2013-11-30T01:35:45.117 回答
7

将文件 genesis_model.php 放在 core 目录中

于 2011-07-04T20:36:48.880 回答
5

将您的 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.

于 2011-07-04T13:02:04.960 回答
2

您必须在 Human_model.php 中包含 Genesis_model,如下所示:

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

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

于 2011-07-04T12:45:25.950 回答
2

其他解决方案

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

    public function get(){
        return 'child';
    }
}
?>
于 2014-09-01T11:55:59.437 回答