Created
July 21, 2011 04:21
-
-
Save jondavidjohn/1096485 to your computer and use it in GitHub Desktop.
Base Codeigniter Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php if (! defined('BASEPATH')) exit('No direct script access'); | |
class Base_m extends CI_Model { | |
protected $table_name; | |
protected $pk_field; | |
public function __construct() | |
{ | |
parent::__construct(); | |
} | |
public function get_all() | |
{ | |
$query = $this->db->get($this->table_name); | |
if ($query->num_rows() > 0) | |
{ | |
return $query->result(); | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
public function get($id) | |
{ | |
$this->db->where($this->pk_field, $id); | |
$result = $this->get_all(); | |
if (count($result) == 1) | |
{ | |
return $result[0]; | |
} | |
else | |
{ | |
return false; | |
} | |
} | |
public function create($data) | |
{ | |
return $this->db->insert($this->table_name, $data); | |
} | |
public function update($pk, $data) | |
{ | |
$this->db->where($this->pk_field, $pk); | |
return $this->db->update($this->table_name, $data); | |
} | |
public function delete($key, $value = NULL) | |
{ | |
if ($value == NULL) | |
{ | |
return $this->db->delete($this->table_name, array($this->pk_field => $key)); | |
} | |
else | |
{ | |
return $this->db->delete($this->table_name, array($key => $value)); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php if (! defined('BASEPATH')) exit('No direct script access'); | |
class Implemented extends Base_m { | |
function __construct() | |
{ | |
$this->table_name = 'implemented_table'; | |
$this->pk_field = 'id'; | |
parent::__construct(); | |
} | |
/*** | |
* Stack on more specific functions on top of the basic CRUD provided | |
* by the base model easily | |
*/ | |
function get_by_user_id($user_id) | |
{ | |
$this->db->where('user_id', $user_id); | |
return parent::get_all(); | |
} | |
} | |
/*** | |
$this->load->model('implemented'); | |
$all_items = $this->implemented->get_all(); | |
$all_items_by_user_id = $this->implemented->get_by_user_id($user_id); | |
etc... | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment