Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Inherit A Model from Another Model in CodeIgniter

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.

like image 400
dqiu Avatar asked Jul 04 '11 08:07

dqiu


2 Answers

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');
like image 160
Josh Avatar answered Oct 27 '22 02:10

Josh


other solution

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

    public function get(){
        return 'child';
    }
}
?>
like image 28
Diaconescu Doru Avatar answered Oct 27 '22 02:10

Diaconescu Doru