CodeIgniter Forums
Loading the database class on demand. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Loading the database class on demand. (/showthread.php?tid=30290)



Loading the database class on demand. - El Forum - 05-10-2010

[eluser]megablue[/eluser]
Is there any elegant way to load the database class on demand whenever I trigger any db->method()? The page was generated from my own cache implementation when there is no query, it is waste of resources to load the database (about 100ms and extra 1MB memory on my machine to load and initialize the object).


Loading the database class on demand. - El Forum - 05-10-2010

[eluser]InsiteFX[/eluser]
autoload

InsiteFX


Loading the database class on demand. - El Forum - 05-10-2010

[eluser]danmontgomery[/eluser]
He's specifically asking how not to use CI's autoload, and __autoload won't work because $this->db won't be defined if the database isn't loaded.

In 2.0 you can set the 'autoinit' configuration in config/database.php which will keep the database from connecting when the class is instantiated... This would probably be the most elegant way. I haven't found any way in 1.7.2 to properly set this (the check is made as soon as the class is loaded, line 135 of DB.php), but you could theoretically extend the DB driver and add the autoinit value, or just take some code from 2.0 (or upgrade/wait for 2.0).

I can't really think of a good way to load the class on demand... You would have to explicitly declare $this->db, and do something like:

Code:
if(!is_a($this->db, 'CI_DB_mysql_driver')) {
    unset($this->db);
    $this->load->database();
}

Which is probably pretty oversimplified.


Loading the database class on demand. - El Forum - 05-10-2010

[eluser]megablue[/eluser]
[quote author="noctrum" date="1273518118"]

Code:
if(!is_a($this->db, 'CI_DB_mysql_driver')) {
    unset($this->db);
    $this->load->database();
}

Which is probably pretty oversimplified.[/quote]

This is exactly what i'm doing, throwing this code around in my models.

I'm thinking of building a skeleton class for db, which will serve as a proxy to 'autoload' database class when db methods get triggered while replacing the $this->db with actual database object.


Loading the database class on demand. - El Forum - 05-10-2010

[eluser]danmontgomery[/eluser]
That might be your best option until an official 2.0 release