[eluser]drewbee[/eluser]
Hey all,
As the continuing process to make things even more easier and allow flexibility, but conform to some kind of standard I have started doing the following in regards to models. Basically, every model will have some kind of get,update,insert and delete. Now, I know a lot of people like to be very specific with their models, but I do not like that. I like to have more control in the controller over what is being used in the model.
As another point of focus and tracking, almost every table I like to have a created and updated date, a who (account id of editor), and a deleted flag. I very rarely have a table without these, so even if it is just a reference table, I include these as well 'just because'.
So, first and foremost, let's extend CI's model and set our constant get, update, insert, and delete methods.
Code:
<?php
class CIEXT_Model extends Model
{
var $table = '';
function __construct()
{
parent::__construct();
}
function get($where = null, $order_by = null)
{
$this->db->select('*');
$this->db->from($this->table);
if ($where)
{
$this->db->where($where);
}
if ($order_by)
{
$this->db->order_by($order_by);
}
$query = $this->db->get();
return $query;
}
function insert($insert = array())
{
if (!is_array($insert))
{
return FALSE;
}
$insert['created'] = date("Y-m-d H:i:s", time());
$insert['updated'] = date("Y-m-d H:i:s", time());
$insert['who'] = $this->session->userdata('account_id');
$this->db->insert($this->table, $insert);
return $this->db->insert_id();
}
function update($set = array(), $where = array())
{
if (!is_array($set) || !is_array($where))
{
return FALSE;
}
$set['updated'] = date("Y-m-d H:i:s", time());
return $this->db->update($this->table, $set, $where);
}
// We still have the option to do an actual data delete if we really
// want too... pass true to the second parameter.
function delete($where = null, $hard_delete = FALSE)
{
$set = array('deleted' => '1');
if ($hard_delete == TRUE)
{
return $this->delete($this->table, $where);
}
else
{
return $this->update_exercise($this->table, $where);
}
}
}
?>
So now, when creating a new model we simply have to specify the table name
Code:
class Accounts extends CIEXT_Model
{
function __construct()
{
parent::__construct();
$this->table = 'accounts';
}
function get_inactive()
{
$where = array('account_status' => 0);
return $this->get($where);
}
}
Usage, of course
Code:
$this->load->model('accounts');
// Get an account
$where = array('account_id' => '3423');
$accounts->get($where);
// Get inactive
$accounts->get_inactive();
Obviously this setup works strictly for the base tables, and will have to be more robust when dealing with joinings, but it gets rid of a lot of repetition for the same functionality.
Thoughts on this?