How to Inherit A Model from Another Model in CodeI

2019-03-26 07:30发布

问题:

i'm using codeigniter for my project and i have this class model which i call Genesis which looks like this:

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

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

and i have another model, stored in the same directory, which extends Genesis_model

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

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

Human_model is used by Human controller

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);
    }
}

if i execute the code, it will produce an error which point to return $this->get(). it reads "Fatal error: Class 'Genesis_model' not found in ...\application\models\human_model.php on line 2".

i use this method because nearly all my models shared almost identical structure. I gather the similar functionality in Genesis while the other models serve only as data suppliers unique to the tables they represent. it works well in my asp.net (vb.net) but i don't how to do it in codeigniter.

is there a way for Human_model to inherit Genesis_model. i don't think i'm allowed to use include('genesis_model.php'). i don't know if it works either.

thanks in advance.

回答1:

Put the file genesis_model.php in the core directory



回答2:

core/MY_Model is good if there's only 1 important superclass for your models.

If you want to inherit from more than model superclass, a better option is to change your autoload configuration.

In application/config/autoload.php, add this line:

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


回答3:

Change your Human_model to this:

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

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

notice the get_human function and the include.



回答4:

You have to include the Genesis_model on your Human_model.php like this:

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

Or you can autoload it on your config/autoload.php file, what I think is stupid =)



回答5:

other solution

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

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