Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Multiple models in Codeigniter 2

How do you set up CI2 to allow extending of multiple models?

I can only get it to extend one model (put in /application/core) named MY_Model (case sensitive).

To choose what model to extend I am doing; in the model..

require_once APPPATH.'core/MY_Another_model.php';
class Test_model extends MY_Another_model {
...
}

I can't find where in the core system code where it states only to allow models that are being extended to be called MY_Model.

Thank you for any and all help.

like image 220
Rooneyl Avatar asked Nov 15 '11 13:11

Rooneyl


2 Answers

I've tried Cubed Eye's way, and it works, but here's another option:

Try adding a model to your autoload.php file. It could inherit from MY_Model (which inherits from CI_Model), and any additional models you load could inherit from it:

class Extended_model extends MY_Model {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Another_model');
    }
}

(models/Extended_model.php)

class Another_model extends Extended_model {
}

(models/Another_model.php)

EDIT: I just realized that you're putting your extended model in the "core" folder. This is only necessary for classes that extend the core CI_* classes (i.e. MY_Controller, MY_Model, MY_Input, etc.). If you have a model extends MY_Model, put it in your models/ folder instead, and don't prefix it with "MY_".

like image 185
landons Avatar answered Oct 15 '22 22:10

landons


As I said in this question about the controllers you just put both classes in the same MY_Model file. This file is used as part of the autoload feature of codeigniter, meaning that it will look for any files with the MY_ (or config defined) prefix.

You don't even need to call the class inside MY_Model you can potentially call it MY_Special_Model and have MY_Another_Model directly underneath

like image 26
Cubed Eye Avatar answered Oct 15 '22 22:10

Cubed Eye