| m u s h i n |mu-shin.ca

 
July 2, 2009

CodeIgniter standard model

Category: Code, General — Tags: , , — Marc Trudel-BĂ©lisle @ 1:14 AM

I have been working with CodeIgniter for a while, for a personal project of mine. Here is the current model all my other model are extending – its a nice way to wrap up the basic standard ways of making certain operations for all models. Following are some notes concerning that code.

class M_core extends Model {

protected $table;

function M_core(){
parent::Model();
$query = $this->db->query("DESC ".$this->table.";");

foreach($query->result() as $row){
$name = $row->Field;
$this->$name = false;
}
}

function get($data=false){
if(!$data)
$query = $this->db->get($this->table);
else
$query = $this->db->get_where($this->table, $data);

return $query->result();
}

function insert($data){

$this->_set_data($data);
unset($this->id);

$this->db->insert($this->table, $this);
$this->id = $this->db->insert_id();
}

function update($data)
{
$this->_set_data($data);

$this->db->where('id', $this->id);
$this->db->update($this->table, $data);
}

function delete($data=false)
{
if(is_array($data))
$this->_set_data($data);

if($this->id)
{
$this->db->where('id', $this->id);
$this->db->delete($this->table);
}
}

private function _set_data($data)
{
foreach($data as $field => $value)
if(isset($this->$field))
$this->$field = $value;
}
}
?>

Some notes:

  1. All functions that can receive data are expecting an array – this as a standard gives me a certain flexibility.
  2. function create unset $this-id so that we don’t try to create an object with an empty id.
  3. _set_data takes only the data for the present columns in the MySQL database. Hence, to add a new variable to the object, just add the column in the MySQL table.
  4. It is not much optimized for querying speed, just for simplicity – I would expect some decent caching architectures would solve most performances problems.
  5. get should have some paging options but – oh well, later.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave your comment

Powered by WordPress