CodeIgniter Forums
How to check if a library exist in a controller? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: How to check if a library exist in a controller? (/showthread.php?tid=65102)



How to check if a library exist in a controller? - agriz - 04-29-2016

PHP Code:
if(file_exists("../libraries/myapp/" ucfirst($library_name).".php")) { 

This code is not working for me.
It is written inside of a controller.

I have a default library and some special libraries.
If special libraries are just the controller names.

If they exist, they should be loaded. Or the default one should be loaded.

PHP Code:
if(file_exists("../libraries/myapp/" ucfirst($library_name).".php")) {
 
   $this->load->library("myapp/".$library_name);
}
else {
 
   $this->load->library("app_default_library");


What is the right way to check the existence of a library?


RE: How to check if a library exist in a controller? - Tpojka - 04-29-2016

Check if object is available:

PHP Code:
$is_loaded is_object(@$this->upload) ? TRUE FALSE;// @ sign suppressed error if object didn't exist
var_dump($is_loaded);
exit; 

Now you just need to make your own method that take a parameter as name of library:

PHP Code:
private function is_lib($lib)
{
 
   return is_object(@$this->{$lib}) ? TRUE FALSE;


PHP is_object function.


RE: How to check if a library exist in a controller? - agriz - 04-29-2016

How can we use
PHP Code:
$this->{$lib
?
Dont we need to load it first?


PHP Code:
$this->load->library($lib); //This lines throws 500 Internal Server Error. Because that library is not available. 



RE: How to check if a library exist in a controller? - Tpojka - 04-29-2016

I understand that you want first to check if library loaded.
If not than you need to load, else you just use that library:

PHP Code:
public function some_other_method()
{
 
   if ( ! $this->is_lib($lib))
 
   {
 
       $this->load->library($lib);
 
   }
 
   // rest of your code
}

private function 
is_lib($lib)
{
 
   return is_object(@this->{$lib}) ?: FALSE;