Welcome Guest, Not a member yet? Register   Sign In
How to Return an Instance of the Loaded Model Class Rather Than The Loader
#1

Good morning all.

I am currently working on a project which requires dynamic switching of database and table. All my application model extends core MY_Model so that i wont have to keep re-writing my basic model functions (create(), read(), update() and delete()).
Here is the constructor in MY_Model.
function __construct($database_connection,$table_name){
   parent::__construct();
   self::$database_connection = $database_connection;
   self::$table_name = $table_name;
}


and a typical model has the below constructor
function __construct()
{
   parent::__construct($this->load->database("db_xxx",true),"table_yyy");
}


The approach works fine but for a very major and important clashing.   Neither $this->load->model("model_name") nor $this->load->model("model_name","object_name") returns the instance of the loaded Model class (unlike the case of loading a view $this->load->view("view_name",array(),true)). Loading a model returns an instance of CI Loader. And also, CI does not allow re-loading of an already loaded model class.

Thus whenever i load a stack of models, the most recent model in the stack always nullify others. I want to believe there is a way around this.

I will be so glad with any assistance provided. Thanks to you all in anticipation.
Reply
#2

(This post was last modified: 06-29-2018, 04:28 AM by Pertti.)

$this->load->model is meant for loading in script file (think of it as making this model code available in principle), not actually associate it to variables.

You probably want to get to is something like this:
PHP Code:
$this->load->model('model_name');
// ... 

$a = new Model_name('db_xxx''table_yyy');
$b = new Model_name('db_yyy''table_xxx'); 
Reply
#3
Thumbs Up 

Pertti, thank you so much.  I am deeply grateful to you.  I took into your correction, changed MY_Model class variables from 

private static $database_connection;
private static $table_name;


to non-static variables, modified the MY_Model constructor to 
function __construct($database_connection,$table_name){
   parent::__construct();
   
   $this->database_connection = $database_connection;
   $this->table_name = $table_name;
}


and then everything was perfectly ok. Right now, i dont need to reload an already loaded model class and can load a stack of unlimited model classes at a time without any single clash nor unwanted overrides.

Once again, Thank you Pertti[Image: thumbsup.gif][Image: thumbsup.gif][Image: thumbsup.gif]
Reply
#4

No worries, glad to help Smile
Reply




Theme © iAndrew 2016 - Forum software by © MyBB