Codeigniter loading model in the library

I am using codeigniter 2.1.3

I am trying to load a model from a library. Initially, my code in the construction in the library is as follows:

$this->CI=& get_instance(); $this->CI->load->database('default') 

Then in one of my library methods

when i tried the line below it doesn't work

 $this->load->model('model_name') 

but when i tried this

 $this->CI->load->model('model_name','',TRUE) 

it works, can anyone explain what the CI instance is for, and 2 additional parameters when loading the model? Thanks in advance.

+11
codeigniter
source share
3 answers

A library is not necessarily part of how CodeIgniter works.

It can be a home library to solve the problem you want to do in your CI application.

This means that if you want to use any CI helpers, models, or other libraries, you need to do this through a CI instance. This is achieved by the fact that:

 public function __construct() { $this->CI =& get_instance(); } 

By assigning an instance to your member library named CI, all CI-related helpers, models, and libraries can be loaded via $this->CI . Trying to do this only with $this , you only reference the current library, not the CI instance.

To load the model correctly, in your library $this->CI->load->model('model_name'); enough. The second parameter allows you to access your model using a different object name. The third parameter is not needed to load models, but allows you to automatically load the database driver.

If you want to access your model through the same element:

 $respone = $this->CI->model_name->method(); 
+27
source share

You can say that the model load function is automatically connected by passing TRUE (boolean) according to the third parameter, and the connection settings will be used, as defined in the database configuration file:

 $this->load->model('Model_name', '', TRUE); 

You can find out about this at the end of the page of this link below.

http://ellislab.com/codeigniter/user-guide/general/models.html

+2
source share

I have a very simple code that you must use to load the model into the library

 <?php class Custom_lib { private $_CI; public function __construct() { $this->_CI = & get_instance(); $this->_CI->load->model('Dynamic_Model','dm'); } function currentSession() { $session = $this->_CI->dm->fetchSingleData('id,session','session',array('is_active'=>1)); return $session; } } 

I hope this code helps you

+1
source share

All Articles