Posted by scotti3g
Most models I create need to access the database. You can easily have CI automatically load the database class by setting a 3rd parameter to true when loading your model:
$this->load->model('your_model', '', true);
The 2nd parameter, which in this case was left blank, is used if you want to assign a different object name to the model – something that I have never used.
Has anyone ever actually used a different object name? The reason I ask is because it’s so easy to forget about the 2nd parameter, and sometimes I try to put the true parameter to auto-load the database in the 2nd slot like this:
$this->load->model('my_model', true); // WRONG!
Of course, the easiest solution is to autoload the database through the config, but that can be a little inefficient for apps that don’t use the DB on every page.
Actually you can achieve lazy connecting to DB:
$db['default']['autoinit'] = FALSE;
Sometimes, in certain controllers, my model name clashes with a local variable, so I have to rename it. The dashes in your pseudo model names is throwing me. No way that would work!
I use the pseudo name quite a bit mostly because the model names are sometimes fairly long and I like to use a shortened version when working with them.
Either that or you just sometimes run into common name variable issues and its good to customize a bit more in the code. Still good practice to name it something close though to the model name.
@Sam – Lazy connecting to DB? :) The standard $this->load->database() is still pretty easy for the lazy people hehe ;) Or simply putting the database class in the autoload part of the config.
@Colin – My bad.. you’re right about the dashes in the pseudo model names. I’ll change them to underscores right away. Thanks! :)
@Rob G – Using the pseudo names to shorten long names is very valid. In my latest project I took care of that issue by having some very generic reusable models/classes, then created instances of those classes (at which point shorter names could be introduced).