CodeIgniter standard model
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:
- All functions that can receive data are expecting an array – this as a standard gives me a certain flexibility.
- function create unset $this-id so that we don’t try to create an object with an empty id.
- _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.
- It is not much optimized for querying speed, just for simplicity – I would expect some decent caching architectures would solve most performances problems.
- get should have some paging options but – oh well, later.
