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:

   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: 2462 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
Post rating
1 Star2 Stars3 Stars4 Stars5 Stars (21 votes, average: 4.67 out of 5)
Loading ... Loading ...

  • u3nu3n
    Thanks a lot~~
    your extension save me lot of time! :)
  • Abbas Mandal
    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.

    Abbas
  • Software_Miami
    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.
  • Carlos
    Why not using HMVC & Ignited Record & write a page module (like haughin' did) instead of hacking the core?
    Saves even more time ^^
  • 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);

    with

    $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 :)
  • Ryan Blunden
    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.
  • 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.

    Cheers!
  • 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:\home\codeigniter\system\application\libraries\MY_Model.php on line 196

    and I just can't work out how to get around it... any help would be great!
  • Michael's suggestion actually doesn't work, as I mentioned in my reply to him. You'll have to replace the actual Model.php in system/libraries to make it work. Hope this helps.
  • 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!
blog comments powered by Disqus