I am using codeigniter 2.1.3
I am trying to load a model from the library. Initially my code in the construct in the library looks like this
$this->CI=& get_instance(); $this->CI->load->database('default')
Then in one of my library methods
when I tried the line below it doesnt work
$this->load->model('model_name')
but when I tried this
$this->CI->load->model('model_name','',TRUE)
it works, anyone can explain what the instance of CI refers to and the 2 extra parameters when loading the model? Thanks in advance.
To load your model correctly, in your library, $this->CI->load->model('model_name'); is enough. The second parameter allows you to access your model through a different object name. The third parameter is not necessary for loading models, but allows you to autoload the database driver. Save this answer.
You will load it using: $this->load->library('flavors/chocolate'); You may nest the file in as many subdirectories as you want. Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load function.
$this refers to the current object. Whenever you create an instance like this: $something = new SomeClass(); Then $this refers to the instance that is created from SomeClass , in this case $something . Whenever you are in the class itself, you can use $this to refer to this instance.
Loader, as the name suggests, is used to load elements. These elements can be libraries (classes) View files, Drivers, Helpers, Models, or your own files. Note. This class is initialized automatically by the system so there is no need to do it manually.
A library is not necessarily a part of the way CodeIgniter works.
It could be a homemade library, to solve a task that you want done in your CI application.
This means that if you want to use any of CI's helpers, models or other libraries, you need to do this through the CI instance. This is achieved by doing this:
public function __construct()
{
$this->CI =& get_instance();
}
By assigning the instance to your librarys member named CI, all CI related helpers, models and libraries can be loaded through $this->CI
. By trying to do it only with $this
you are only referring to the current library - not the CI instance.
To load your model correctly, in your library, $this->CI->load->model('model_name');
is enough. The second parameter allows you to access your model through a different object name. The third parameter is not necessary for loading models, but allows you to autoload the database driver.
If you want to access your model through the same member:
$respone = $this->CI->model_name->method();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With