Read the latest web development and design tips at Fred Wu's new blog! :-)
Poke me on GitHub

CodeIgniter – Loading Models and Database in One Hit

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.

  • Digg
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Twitter

Related posts

Tags: , ,

Comments Section

4 Responses to “CodeIgniter – Loading Models and Database in One Hit”

Sidebar might be covered by comments ... consider it a feature! ;)
  1. 1

    Actually you can achieve lazy connecting to DB:

    $db['default']['autoinit'] = FALSE;

  2. 2

    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!

  3. 3

    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.

  4. 4

    @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).

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>