codeigniter correct way to check if libraries/helper/core files is loaded
Solution 1
You can use the native PHP function class_exists() to determine if the class has been defined, before calling it. In same regard, using method_exists() will check if class method exists.
Since helpers are collection of function, not methods, checking can be done using function_exists().
if (class_exists('Library'))
{
$this->library->myMethod();
}
For further info please refer to
http://php.net/manual/en/function.class-exists.php.
http://us.php.net/manual/en/function.method-exists.php
Solution 2
You don't have to check, you just load them wherever you need to be sure to have them.
Using CI's Load library ($this->load->[library|model|helper]
) will always load it just once. You can see this if you turn on your debug logging.
Solution 3
this is codeigniter method to check the loaded libraries.
//If the library is not loaded, Codeigniter will return FALSE
if(!$this->load->is_loaded('session'))
{
$this->load->library('session');
}
Solution 4
Once loaded your instance is store on the controller, so to check if a model has been loaded :
if (isset($this->my_model))
Where $this
is your controller.
Solution 5
The best way to do this is using Codeigniter's Loader
Class. The Loader
aka load
has an inbuilt method is_loaded
. is_loaded
method checks if a class has already been loaded or not.
If the class has not been loaded then is_loaded
returns FALSE, otherwise it returns property name.
Example:
$this->load->library('table');
$this->load->is_loaded('table'); //Returns 'table'
$this->load->is_loaded('blabla_library'); //Returns FALSE
Related videos on Youtube
user1884324
Updated on July 14, 2022Comments
-
user1884324 almost 2 years
i'm using codeigniter 2.
Appreciate if someone could show the correct way to check if the following files :
- library file is loaded?
- helper file is loaded?
- config file is loaded?
- model file is loaded?
- third_party file is loaded?regards
-
Hrvoje Golcic almost 10 yearsAre you sure about this? I include session library several times, the used memory raise significantly, I just tested it out. Codeigniter bug?
-
minboost almost 10 yearsLook at Loader.php and search for 'Second attempt ignored' (NOTE: if you supply custom names, it will create a new instance).
-
Hrvoje Golcic almost 10 yearsYou are right, Codeigniter way is the most efficient way, I did a little benchmark
-
Hrvoje Golcic almost 10 yearsThis is correct way to check but if the reason for checking is to include the library then do not use this. I have made a little benchmark that proves the default Codigniter way of loading libraries is the best way. Look here: stackoverflow.com/questions/19630019/…
-
Hrvoje Golcic almost 10 yearsThis is correct answer to the question, here is a benchmark: stackoverflow.com/questions/19630019/…