Extended Model for CodeIgniter

Feb 2009: An updated version of the code for CodeIgniter 1.7.x can be found here.

I developed this extension of CodeIgniter’s Model last year, but never had the chance to publish it. The main purpose of this extension is to make a dev’s life easy. This extension has been used by several of my devs at RBS and has been proved to increase productivity and reduce the number of painful small queries to write. Their enthusiasm has driven me to post this for the CI fans out there.

Without much babble, let’s get into point. I’ve explained the process of installing it and then showed some example uses. For starter, click here to download it. Now follow these steps to get started:

1. Replace the system/libraries/Model.php file with the attached Model.php (CodeIgniter version 1.6.3)

2. For each of your tables, you will need to create a model file in system/application/models.

3. Lets say we have a “products” table whose schema is as follows:

4. Now we need to create system/application/models/product.php:

5. From any controller, you can load the Model as instructed in the CI manual. Here are some sample usage of the model functions:

7. There are a number of other helpful functions in this file. If you have a careful look, you’ll discover that some of them are really handy.

UPDATE: I forgot to give due credit to the wonderful developers of CakePHP – I’ve taken inspiration from their Model implementation while building this one for CodeIgniter.


MORE UPDATE: Download the version for CodeIgniter 1.7.x here.

32 thoughts on “Extended Model for CodeIgniter

  1. In the world where I live, when you take off the code that someone else built, or steal its ideas, it’s nice to give a credit back. And if you DID take out the source code, you need to abide by their license agreement.

    On this particular case your source code (mainly its method names and implementation) look strangely familiar to CakePHP’s model implementation (for outsiders, concentrate on the method names and signatures):


    To give a small preview of the similarities:

    * $this->data and $this->useDbConfig used on both
    * getAffectedRows()
    * getNumRows()
    * getInsertID()
    * getID()
    * lastQuery()
    * query()
    * remove()

    Well, almost all methods are borrowed from CakePHP implementation.

    So I think you seriously need to revisit your use of open source software and inability to respect its MIT license.

  2. I recommend making the following change to your installation instructions:

    1. Rename the attached Model.php to MY_Model.php and place within your application/libraries directory.

    You should never hack the core – it makes upgrading a pain.

    Thanks for the great library – I posted a link to this from my blog as well as some of my own comments concerning it! A great contribution to the community.

  3. @Wales,

    Thanks for the appreciation. I actually tried not to hack into the core but the overloading of base CI classes didn’t work with the Model class.

    If you can get it working in any way, I’d be more than happy to follow that and update the install steps accordingly.

    Thanks a lot.

  4. @Mariano

    Thank you very much for reminding me the source. It is my bad that I completely forgot to mention the credit to CakePHP’s model implementation.

    I actually created this in the middle of last year and have been using from then. The day I posted it here, I was actually rushing – so the due credit was missing. I’m going to update the post with a mention to this.

    And btw, I’ve only taken inspiration for the methods and variable names. The code utilizes the Active Record library of CodeIgniter. Also, it doesn’t burden the developer with the associations.

    Thanks a lot.

  5. @taewoo: before you post, READ. That works on every level. He DID say he FORGOT to credit CakePHP until I reminded him, so you should double read the comments before you call me anal.

  6. @Emran

    Great work, Thats what I am saying since you’ve showed me the code last year sometime. But unfortunately I have left using CI.

    Thanks for pointing out that method names were borrowed from CakePHP, but that clearly didnt disrespect MIT license model. It is not a derived work but written from scratch, did you note that? I appreciate your observation but I still think you were a bit rough at this one. Anyway, thanks. No hard feelings.

  7. As PHPFour’s model is not an extension but a replacement, here’s how I would set it up.

    Open PHPFour’s ‘Model.php’ and do the following to it:


    class Model {


    class CI_Model {


    function Model()


    function CI_Model()

    Save the file as ‘Model.php’ and place it in:


    This is the proper way to replace core libraries. Source:

  8. Although after testing, that doesn’t work o.O

    Leaving out the CI_ and putting it in application/libraries allows it to run perfectly fine.

    I wonder why CodeIgniter doesn’t allow the CI_ override for the Model?

  9. Having been (and currently beeing) on several open source projects I know this is not unheard of. But people like Ryan on his comment above (showing that his brain consists only of derogative terms) certainly do not help the projects.

    For the sake of CI, I hope you have more of the “other kind” of people. You know, people that KNOW something about something, and HELP the project back, for a change.

  10. @Ryan: I fully agree with Mariano and would misjudge the CI community in the same way, seeing your response.

    What Mariano did was just to remind me something that I forgot, although in a bit rough way, but he had no bad intention in mind and I thanked him for that.

    We’re all community enthusiastic, let’s not create divisions and point fingers.

  11. @Mariano Iglesias

    You really want him to re-name “query(), “getNumRows()”, “$this->data” and other method/property names? These are standard method names used by pretty much every database abstraction layer in the history of programming.

    Saying phpfour isn’t respecting the MIT license is a bit harsh. He’s just looking at other libraries for inspiration and building his own. Nothing wrong with that.

  12. I’d like to try using this, and I’ve tried it using Michael’s suggestion, eg renaming to MY_Model etc, but I keep getting this error:

    Fatal error: Call to undefined method CI_DB_mysql_driver::field_names() in C:homecodeignitersystemapplicationlibrariesMY_Model.php on line 196

    and I just can’t work out how to get around it… any help would be great!

  13. Well, as always after posting a ‘help me!’ question, I’ve worked it out.

    Replace Line 196 of MY_Model.php:

    $this->fields = $this->db->field_names($table);


    $this->fields = $this->db->list_fields($table);

    as field_names() is deprecated, and clearly in 1.7.0 does not work!!

    Hope this helps someone else πŸ™‚

  14. Thanks for the reply, Emran! I hadn’t seen your reply when I posted my fix below.

    What I’ve done (in addition to the fix below) is rename it to MY_Model.php, placed it in system/application/libraries, updated the constructor to class MY_Model extends Model, and that’s literally it. It’s all working so far – I’ll post back if I hit another snag πŸ™‚

    It may well be something they’ve fixed in these latest updates to CI, so you may wish to try it again, and if it works for, update your instructions accordingly.

    Thanks for your contribution – it looks like it will be very useful!

  15. Thanks Jacob for pointing this out !!! I’ve been waiting for long to have CI support this. I will write a separate post with the update and a few additional features I planned long ago (probably post date: first week of Nov).

    Everybody, please follow Jacob’s two comments if you’re using CodeIgniter 1.7.0.


  16. Forgive the personality analysis, but your seemingly irate attitude towards the author necessitated commentary.

    Do bear in mind that you’re a guest on this website, not an unpaid asshole.

    Your message is true, but your delivery is definitely flawed. I’d recommend trying to be a little more polite, or you’ll keep getting comments from people like Ryan. While I agree with what you said, the way you came across was pretty overwhelmingly full of douchebaggery. I have not personally visited the CakePHP forums but if they’re full of people such as yourself who display a genuine “inability” to be polite, I don’t plan on visiting anytime soon.

    It is rather apparent that you’re a CakePHP fan, but don’t turn it into some form of irrational zeal. Step one would be to resist all caps. Step two would be to assume that other people aren’t as brilliant as you, and don’t have the MIT license memorised. Step three would be to perhaps quietly suggest that the author credit the source that shows definite similarity to his code snippets, instead of full-force attacking him.

    Thanks for the info, Emran. I was trying to extend Model.php, and I eventually just popped a customised copy of “Model.php” in my APPPATH/libraries folder and overrode the default Model file altogether.

  17. Why not using HMVC & Ignited Record & write a page module (like haughin’ did) instead of hacking the core?
    Saves even more time ^^

  18. Emran and others,
    Thanks for the innovative work Emran. The comments also proved extremely helpful.

    @Michael Wales: Extremely helpful and encouraging as always (esp. in the CI forums).

    @Jacob & @stensi: Thanks for the additions.

    @ryan & @joshdavey & @abe: Good call all around. To come on someone’s forum and sound so arrogant shows a lack of taste, respect and manners.

  19. The only way I could get this to work in Code Igniter 1.7.0 was to replace the Model.php in the system/libraries directory as the above methods didn’t work for me.

    This could be because I’m using Matchbox 0.9.4 which hasn’t been updated to include a lot of the new code in Loader.php yet…

    But apart from that, this is such a time saver and a brilliant piece of kit to add to your Code Igniter arsenal.

    Thanks heaps for creating it and looking forward to seeing the additional features you’ve got planned.

  20. Thanks Emran for this blog.Though Iam not a guru like some of you here,but i like the framework.
    Iam a newbie to CI.Thanks again.


  21. Hello,
    very nice work,has anybody developed multi tables model using mysql views?


  22. Hi there,

    Great library- thank you sharing. I’m having a bit of trouble though. I’m getting duplicate entry errors when I try to save a model object. It appears that it’s trying to insert when it should update. Here’s the code in one of my custom libraries that uses an extended model:

    $membership = $this->CI->membership_model->find("merchantId = '$merchantId' AND customerId = '$customerId'");

    if($membership) { // this membership already exists
    else { // this is a new membership
    $membership['merchantId'] = $merchantId;
    $membership['customerId'] = $customerId;
    $membership['points'] = 1;
    $membership['created'] = date("Y-m-d H:i:s");


    And this is the constructor for “membership_model.php”:

    function __construct() {
    // Call the Model constructor
    $this->primaryKey = 'membershipId';

    What am I doing wrong here?

Comments are closed.