Codeigniter: My MY_Model or “How not to repeat yourself”

Often times I find myself doing the same queries over and over again for each table used by an application. This is why I needed to create an “universal” model in order to avoid repetition. Codeigniter lets you do that by allowing you to create a “MY_Model” inside the core folder of your application.

I haven’t really tried it, and I sure hope you won’t find any errors in it.

The methods are as follows:

get_all()

public function get_all($where_arr = NULL, $order_by_var_arr = NULL, $select = NULL)

All the arguments of the method are optional but, if you need to have an array with conditions that the records have to comply to, you can use the $where_arr array(). Also, if you need to order by a certain column you can use either a string with the name of the column or an array having the elements: “name of the column” and “type of ordering”. You can also choose to select only certain columns by enumerating them in a string.

The method will return an object with the results.

get()

get($where_arr = NULL)

The get() method must receive an array with the condition that has to be met, and will return only one row.

The method will return the result row.

insert()

insert($columns_arr)

The insert() method must receive an array with the columns and the afferent values you want to insert.

update()

update($columns_arr, $where_arr)

The update() method must receive an array with the columns you want to update and also the array with the conditions that the rows must meet in order to be updated.

The method will return an integer with the number of affected rows.

delete()

delete($where_arr)

The delete() method will delete the rows that respect the conditions inside the $where_arr array.

The method will return an integer with the number of deleted rows.

What to do with MY_Model.php

You should save the MY_Model.php file inside the application’s core folder.

After you save it, you can call it from within any model you create by extending the model as follows:

class Any_model extends MY_Model
{
  public function __construct()
  {
    parent::__construct();
    $this->table ='your_table';
  }
//... other methods that you want to use
}

As you can see, you must extend the MY_Model and in the constructor you must name your model’s main table.

Now you can simply use the methods on any model that extends the MY_Model class.

Now, let me show you my MY_Model:

<?php

class MY_Model extends CI_Model
{
  protected $table;
  public $where_arr = NULL;
  public $order_by_arr = NULL;
  public $cols_sel = NULL;
  public $cols_upd = NULL;

  function __construct()
  {
    parent::__construct();
  }

  /** retrieve all records from DB
   *
   * @param array $where_arr
   * @param var|array $order_by_var_arr
   * @param var $select
   * @return object
   */
  public function get_all($where_arr = NULL, $order_by_var_arr = NULL, $select = NULL)
  {
    if(isset($where_arr))
    {
      $this->db->where($where_arr);
    }
    if(isset($order_by_var_arr))
    {
      if(!is_array($order_by_var_arr))
      {
        $order_by[0] = $order_by_var_arr;
        $order_by[1] = 'asc';
      }
      else
      {
        $order_by[0] = $order_by_var_arr[0];
        $order_by[1] = $order_by_var_arr[1];
      }
      $this->db->order_by($order_by[0],$order_by[1]);
    }
    if(isset($select))
    {
      $this->db->select($select);
    }
    $query = $this->db->get($this->table);
    echo $this->db->last_query();
    if($query->num_rows()>0)
    {
      foreach($query->result() as $row)
      {
        $data[] = $row;
      }
      return $data;
    }
    else
    {
      return FALSE;
    }
  }

  /**
   * Retrieve one record from DB
   * @param type $where_arr
   * @return object
   */
  public function get($where_arr = NULL)
  {
    if(isset($where_arr))
    {
      $this->db->where($where_arr);
      $this->db->limit(1);
      $query = $this->db->get($this->table);
      if($query->num_rows()>0)
      {
        return $query->row();
      }
      else
      {
        return FALSE;
      }
    }
    else
    {
      return FALSE;
    }
  }
  /**
   * Insert a record into DB
   * @param type $columns_arr
   * @return int insert id
  */
  public function insert($columns_arr)
  {
    if(is_array($columns_arr))
    {
      if($this->db->insert($this->table,$columns_arr))
      {
        return $this->db->insert_id();
      }
      else
      {
        return FALSE;
      }
    }
  }
  /**
   * Update record(s)
   * @param type $columns_arr
   * @param type $where_arr
   * @return int affected rows
  */
  public function update($columns_arr, $where_arr = NULL)
  {
    if(isset($where_arr))
    {
      $this->db->where($where_arr);
      $this->db->update($this->table,$columns_arr);
      if($this->db->affected_rows()>0)
      {
        return $this->db->affected_rows();
      }
    }
    else
    {
      return FALSE;
    }
  }
  /**
   * Delete row(s)
   * @param type $where_arr
   * @return int affected rows
  */
  public function delete($where_arr = NULL)
  {
    if(isset($where_arr))
    {
      $this->db->where($where_arr);
      $this->db->delete($this->table);
      return $this->db->affected_rows();
    }
    else
    {
      return FALSE;
    }
  }
}

 

9 comments

    1. Well, What I wrote there is not plain MySQL queries. Is actually ActiveRecord, which is also an ORM, even if is not that advanced as RedbeanPHP ORM. In my opinion (and ofcourse I don’t expect everyone to take my word for it…), ORMs like Redbean are good for rapid development, but are also a bit dangerous considering that you can make databases, tables or columns on the fly with them. You can develop really fast with them, but also you can make mistakes by simply writing wrong a column’s name, which can end up with creating that column.

    1. Hello. This is not a library. Is the same ol’ model with a twist. The idea behind the MY_Model philosophy is that you don’t need to repeat yourself inside the other models. If you have specific queries (i.e. joins), you must have those in their respective models though. The MY_Model queries can be applied to all the models, in the detriment of specificity. If you need me to post a tutorial about joining tables with Codeigniter ActiveRecord, just leave a reply.

  1. I’m really interested in tutorial about joining tables with Codeigniter ActiveRecord. If you could take some time for it I’d really appreciate it. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.