Extended Model for CodeIgniter

12 July 2008 » In Code Igniter, PHP, Programming, RBS »

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:

   1: CREATE TABLE `products` (
   2:       `id` int(11) NOT NULL auto_increment,
   3:       `title` varchar(50) NOT NULL,
   4:       `description` text NOT NULL,
   5:       `color` varchar(20) NOT NULL,
   6:       `price` float NOT NULL,
   7:       `category_id` int(11) NOT NULL,
   8:       `featured` char(1) NOT NULL,
   9:       `enabled` char(1) NOT NULL,
  10:       `visits` int(1) NOT NULL,
  11:       `created` int(11) NOT NULL,
  12:       `modified` int(11) NOT NULL,
  13:       PRIMARY KEY  (`id`)
  14:     ) ENGINE=MyISAM;

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

   1: <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
   2:  
   3:     class Product extends Model {
   4:  
   5:         function Product()
   6:         {
   7:             // Call the Model constructor
   8:             parent::Model();
   9:             
  10:             // Load the associated table
  11:             $this->loadTable('products');
  12:         }
  13:  
  14:     }

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

   1: function products()
   2:     {
   3:         // Load the model in the default way
   4:         $this->load->model('Product');
   5:         
   6:         // Total # of products
   7:         echo $this->Product->findCount();
   8:         
   9:         // Total # of featured products
  10:         echo $this->Product->findCount("featured = 'Y'"); 
  11:         
  12:         // Retrieve ALL the products
  13:         $allProducts = $this->Product->findAll(); 
  14:         
  15:         // Retrive id, title and price of top 10 products (based on popularity) that are enabled
  16:         $topProducts = $this->Product->findAll("enabled = 'Y'", 'id, title, price', 'visits DESC', '0', '10');
  17:         
  18:         // Retrive id, title and price of the 1st most popular product that is enabled
  19:         $topProducts = $this->Product->find("enabled = 'Y'", 'id, title, price', 'visits DESC', '0', '10'); 
  20:         
  21:         // Retrieve the product with id = 1
  22:         $oneProduct = $this->Product->read(1); 
  23:         
  24:         // Retrive the price of the product whose id = 1
  25:         $productPrice = $this->Product->field('price', 'id = 1'); 
  26:         
  27:         // Single array with the titles of all the enabled products
  28:         $productArr = $this->Product->generateSingleArray("enabled = 'Y'", 'title'); 
  29:         
  30:         // Insert a new product in the db
  31:         $newProductId = $this->Product->insert(array('title' => 'New Product', 'price' => '10.99')); 
  32:         
  33:         // Update the price of the newly added product
  34:         $updProduct = $this->Product->save(array('price' => '20.00'), $newProductId); 
  35:         
  36:         // Delete the product
  37:         $this->Product->remove($new_product_id);
  38:     }

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.

Download

Model.php
Extended Model for CodeIgniter
Downloaded: 2725 times

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

Share and Enjoy:
  • Digg
  • DZone
  • Twitter
  • Posterous
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Technorati
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Simpy
  • Ping.fm
  • Tumblr

Tags: , ,

Trackback URL

20 Comments on "Extended Model for CodeIgniter"

  1. admin
    Anis uddin Ahmad
    12/07/2008 at 4:00 pm Permalink

    Thanks a lot man.
    You’ve saved CodeIgniter developers valuable time. :D

  2. admin
    Mariano Iglesias
    14/07/2008 at 11:32 pm Permalink

    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):

    https://trac.cakephp.org/browser/branches/1.2.x.x/cake/libs/model/model.php

    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.

  3. admin
    joeri.cochuyt
    15/07/2008 at 12:32 am Permalink

    tnx, very handy indeed.

  4. admin
    Michael Wales
    15/07/2008 at 1:33 am Permalink

    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.

  5. admin
    Emran Hasan
    15/07/2008 at 2:23 am Permalink

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

  6. admin
    Emran Hasan
    15/07/2008 at 2:28 am Permalink

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

  7. admin
    pengekcs
    16/07/2008 at 12:51 am Permalink

    Nice one there. Thanks for posting it. Small, but nice addition to CI. ;)

  8. admin
    taewoo
    19/07/2008 at 12:47 am Permalink

    Good one.

    @mariano – Damn dude. Relax. He did thank CakePHP for their inspiration. NO need to be so anal.

  9. admin
    Mariano Iglesias
    19/07/2008 at 8:54 pm Permalink

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

  10. admin
    Storyteller
    21/07/2008 at 12:51 pm Permalink

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

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

  11. admin
    stensi
    23/07/2008 at 8:00 am Permalink

    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:

    Change:

    class Model {

    To:

    class CI_Model {

    Change:

    function Model()

    To:

    function CI_Model()

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

    application/libraries

    This is the proper way to replace core libraries. Source:
    http://codeigniter.com/user_guide/general/core_classes.html

  12. admin
    stensi
    23/07/2008 at 8:22 am Permalink

    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?

  13. admin
    Ryan
    03/08/2008 at 7:39 am Permalink

    @Mariano Douchebag Boy

    Go away you miserable creature. Take your nastiness to a cake forum.

  14. admin
    Mariano Iglesias
    08/08/2008 at 7:13 pm Permalink

    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.

  15. admin
    Emran Hasan
    08/08/2008 at 7:34 pm Permalink

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

  16. admin
    joshdavey
    19/08/2008 at 1:00 am Permalink

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

  17. admin
    Mariano Iglesias
    19/08/2008 at 1:40 am Permalink

    @joshdavey: why do a lot of people INSIST ON NOT READING before posting? Check the previous messages, this was SOLVED long ago.

  18. admin
    haran
    20/08/2008 at 9:20 pm Permalink

    Great work. It saves us a lot of time.

  19. admin
    reneegate
    08/07/2010 at 5:25 pm Permalink

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

    reneegate

Trackbacks

  1. [...] original version of the Extended Model for CodeIgniter has been serving many people well. Although most users loved [...]

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to Comments