Model library for CodeIgniter

A set of methods to speed up your development for CodeIgniter 1.x. Update for CodeIgniter 2 is available.

Model library

system/application/libraries/MY_Model.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class MY_Model extends Model {
 
	var $table = "";
 
    function My_Model()
    {
        parent::Model();
	$this->load->database();
    }
 
	function insert($data)
	{
		$this->db->insert($this->table, $data);
		return $this->db->insert_id();
	}
 
	function find_id($id)
	{
		if ($id == NULL)
		{
			return NULL;
		}
 
		$this->db->where('id', $id);
		$query = $this->db->get($this->table);
 
		$result = $query->result_array();
		return (count($result) > 0 ? $result[0] : NULL);
	}
 
	function find_all($sort = 'id', $order = 'asc')
	{
		$this->db->order_by($sort, $order);
		$query = $this->db->get($this->table);
		return $query->result_array();
	}
 
	function update($id, $data)
	{
		$this->db->where('id', $id);
		$this->db->update($this->table, $data);
	}
 
	function delete($id)
	{
		if ($id != NULL)
		{
			$this->db->where('id', $id);			
			$this->db->delete($this->table);			
		}
	}	
}
 
/* End of file MY_Model.php */
/* Location: ./system/application/libraries/MY_Model.php */

Use

Create your model

system/application/models/book.php

<?php
class Book extends MY_Model {
 
	function Book()
	{
		parent::MY_Model();
		$this->table = 'book';
	}
 
/* End of file book.php */
/* Location: ./system/application/models/book.php */

In your controller

insert

$this->load->model('book');
 
$book = array();
$book['title'] = 'The Black Dahlia';
$book['author'] = 'James Ellroy';
 
$this->book->insert($book);

find by id

$this->load->model('book');
 
$book = $this->book->find_id('47');
 
echo $book['title'];

find list

$this->load->model('book');
 
$book_list = $this->book->find_all('title', 'asc');
 
foreach ($book_list as book)
{
  echo $book['title'];
}

delete

$this->load->model('book');
 
$this->book->delete('47');
 

Feedback