CodeIgniter Forums
practical to autoload libraries like this? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: practical to autoload libraries like this? (/thread-20536.html)



practical to autoload libraries like this? - El Forum - 07-13-2009

[eluser]ntheorist[/eluser]
in the Controller, or Controller extending class :
Code:
function __get($name)
{
    // Return return value
    if (isset($this->{$name})) return $this->{$name};
    
    // Will exit if not found
    $this->load->library($name);
    
    return $this->{$name};
}

i realize automagic php functions can be overused and not so great performance-wise, but this might work as an alternative to the autoload config. The only thing is this only loads libraries, but those tend to be the bulkiest parts of an app and would call it up only when needed. Sure its easy just to write $this->load->library() but i'm lazy! Tongue


n


practical to autoload libraries like this? - El Forum - 07-13-2009

[eluser]wiredesignz[/eluser]
Not really practical.

Any class variable not explicitly defined will cause __get() to be triggered. Not just missing libraries.


practical to autoload libraries like this? - El Forum - 07-13-2009

[eluser]Michael Wales[/eluser]
I don't see any problem with it - other than breaking PHP4 compatibility.

Edit:Other than wired's comment - too much to drink to think it all out, thanks to the excellent community - you get more than one inebriated answer!


practical to autoload libraries like this? - El Forum - 07-13-2009

[eluser]garymardell[/eluser]
I think Michael Wales himself is inebriate.


practical to autoload libraries like this? - El Forum - 07-13-2009

[eluser]ntheorist[/eluser]
lol i got a little drunk just from reading his reply Smile

@wired not only that, it would exit with an error if the variable you tried to access wasn't a valid library. This just means you have to define all your class variables, which one should do anyway imo. Also i'd limit it to the Controller scope where i think most runtime library loading is done.

it just seems that the lazy loading of classes is one of the better ways to improve performance.


practical to autoload libraries like this? - El Forum - 07-13-2009

[eluser]wiredesignz[/eluser]
You could try something like this. Just be sure to check how often it is being triggered unnecessarily.

Code:
function __get($name)
{
    $name = ucfirst(strtolower($name));

    if(is_file(BASEPATH.'libraries/'.$name.EXT) OR is_file(APPPATH.'libraries/'.$name.EXT)) {
        $this->load->library($name);
    }
}