CodeIgniter Forums
When to load database? - 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: When to load database? (/showthread.php?tid=40643)



When to load database? - El Forum - 04-14-2011

[eluser]gunnarflax[/eluser]
Where is the most appropriate location to load the database ($this->load->database())? Should I do it in the model or the controller? When doing it from the model I don't have to worry about it in the controller but is that unprofessional?


When to load database? - El Forum - 04-14-2011

[eluser]jleequeen[/eluser]
I do neither. I autoload the database via the config file.


When to load database? - El Forum - 04-14-2011

[eluser]gunnarflax[/eluser]
But if my application doesn't use the database in every controller then that is a waste of resources. If you would have to load the database from either the controller or the model, which would you choose?


When to load database? - El Forum - 04-14-2011

[eluser]jleequeen[/eluser]
True, but I suppose I do it that way because the majority of my application use databases enxtensively, and the few pages that are totally static really don't suffer from any problems in speed. If I had to load it in one place or the other, I would choose the controller. If it's used it more than a couple methods, then I would just load it in the constructor. Otherwise, if it's only used in one or two methods, then you could just load it in those specific methods.


When to load database? - El Forum - 04-14-2011

[eluser]gunnarflax[/eluser]
But if a model relies on the use of a database, wouldn't it make more sense to always load it from the model so that it doesn't get forgotten?


When to load database? - El Forum - 04-14-2011

[eluser]danmontgomery[/eluser]
The general consensus is that all database interaction should be done in the model, so it would make sense to load it there if you don't want to autoload it.


When to load database? - El Forum - 04-14-2011

[eluser]gunnarflax[/eluser]
Yeah, that makes sense. Thank you for your answer! I hate not having rules for the code structure, I always look back and think "maybe it's better the other way around?". Thanks I'll do it in the model!