Skip to content

Instantly share code, notes, and snippets.

@channainfo
Last active October 13, 2016 05:53
Show Gist options
  • Save channainfo/d54bd56c3b9d3a291509be69884327e4 to your computer and use it in GitHub Desktop.
Save channainfo/d54bd56c3b9d3a291509be69884327e4 to your computer and use it in GitHub Desktop.
Active record model mapper in Codeignite CI2
<?php
class ActiveRecordModel extends CI_Model {
protected $_errors = array();
protected $_changes = array();
protected $_not_sql_fields = array('_errors', '_changes', '_not_sql_fields');
// define your table primary key name here
static function primary_key() {
return 'id';
}
// define the name of your table
static function table_name() {
throw new Exception("You must overide this method to return your database table name");
}
//define your class name php older version
static function class_name() {
throw new Exception("You must overide this method to return your model name");
}
//if you have fields in model that are not part of db table field list them down here
static function accessible_fields(){
return array();
}
static function serialize_fields(){
return array();
}
function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
function get_errors() {
return $this->_errors;
}
function get_changes() {
return $this->_changes();
}
function new_record() {
return !$this->id();
}
function id() {
$primary_key = static::primary_key();
return $this->{$primary_key};
}
function load_other_model($model_name) {
$CI =& get_instance();
$CI->load->model($model_name);
return $CI->$model_name;
}
function current_time() {
return date("Y-m-d H:i:s");
}
//create create uniqueness validation for this shi**y framework
function uniqueness_field($field_name) {
$table_name = static::table_name();
$unique_validator = "is_unique[{$table_name}.{$field_name}]";
$escape_unique_validator = "";
if($this->new_record())
return $unique_validator;
$class_name = static::class_name();
$record = $class_name::find($this->id());
return $this->$field_name == $record->$field_name ? $escape_unique_validator : $unique_validator;
}
static function timestampable() {
return false;
}
function exclude_field($field_name){
$fields = array_merge($this->_not_sql_fields, static::accessible_fields());
return in_array($field_name, $fields);
}
function set_attribute($field, $value){
if($this->exclude_field($field) || $field == static::primary_key())
return;
$this->_changes[$field] = array($this->$field, $value);
$this->$field = $value;
}
function set_attributes($datas) {
$this->_changes = array();
foreach($datas as $field => $value)
$this->set_attribute($field, $value);
}
function sql_attributes(){
$attributes = array();
foreach ($this as $field => $value) {
if($this->exclude_field($field) || $field == static::primary_key() )
continue;
$attributes[$field] = static::is_serialized($field) ? serialize($value) : $value;
}
return $attributes;
}
function copy_object($record) {
foreach($record as $field => $value) {
if($this->exclude_field($field))
continue;
$field_value = static::is_serialized($field) ? unserialize($value) : $value;
$this->$field = $field_value;
}
return $this;
}
static function is_serialized($field) {
return in_array($field, static::serialize_fields());
}
static function all($conditions=array(), $page=null, $order_by=null ){
$limit = 10;
$class_name = static::class_name();
$active_record = new $class_name;
foreach($conditions as $field => $value){
if(is_array($value))
$active_record->db->where_in($field, $value);
else
$active_record->db->where($field, $value);
}
$active_record->db->from(static::table_name());
if($page) {
$offset = $page < 2 ? 0 : ($page-1) * $limit;
$active_record->db->limit($limit);
$active_record->db->offset($offset);
}
if($order_by)
$active_record->db->order_by($order_by);
$query = $active_record->db->get();
$records = array();
foreach( $query->result() as $record){
$active_record = new $class_name;
$active_record->copy_object($record);
$records[] = $active_record;
}
return $records;
}
static function find_by($conditions){
$class_name = static::class_name();
$active_record = new $class_name;
$active_record->db->from(static::table_name());
$active_record->db->where($conditions);
$query = $active_record->db->get();
if($query->num_rows() == 0)
return null;
$result = $query->result();
$find_record = new $class_name;
$record = $result[0];
$find_record->copy_object($record);
return $find_record;
}
static function find($id){
$class_name = static::class_name();
$active_record = new $class_name;
$primary_key = static::primary_key();
$active_record->db->from(static::table_name());
if(is_array($id)){
if(count($id) == 0)
return array();
$active_record->db->where_in($primary_key, $id);
}
else
$active_record->db->where(array($primary_key => $id));
$query = $active_record->db->get();
if($query->num_rows() == 0)
return null;
$result = $query->result();
if(is_array($id)){
$find_records = array();
foreach($result as $record) {
$find_record = new $class_name;
$find_record->copy_object($record);
$find_records[] = $find_record;
}
return $find_records;
}
else {
$find_record = new $class_name;
$record = $result[0];
$find_record->copy_object($record);
return $find_record;
}
}
function insert(){
if(static::timestampable()) {
$this->created_at = $this->current_time();
$this->updated_at = $this->current_time();
}
$this->db->insert(static::table_name(), $this->sql_attributes());
if($this->db->affected_rows() == 0)
return false;
else{
$primary_key = static::primary_key();
$this->{$primary_key} = $this->db->insert_id();
return true;
}
}
function update() {
$class_name = static::class_name();
if(static::timestampable())
$this->set_attribute('updated_at', $this->current_time());
$this->db->where('id', $this->id());
$this->db->update(static::table_name(), $this->sql_attributes());
if($this->db->affected_rows() == 0)
return false;
else
return $this;
}
function delete(){
$this->db->delete(static::table_name(), array('id' => $this->id()));
if($this->db->affected_rows() == 0)
return false;
else
return true;
}
function update_attributes($datas){
$this->set_attributes($datas);
$class_name = static::class_name();
if(static::timestampable())
$this->set_attribute('updated_at', $this->current_time());
if(!$this->validate()){
return false;
}
$this->db->where('id', $this->id());
$this->db->update(static::table_name(), $this->sql_attributes());
if($this->db->affected_rows() == 0)
return null;
else{
return $this;
}
}
/* validator requires data from $_POST */
function set_data_to_validate(){
foreach($this as $field => $value) {
if($this->exclude_field($field))
continue;
$_POST[$field] = $value;
}
}
function validate(){
$this->set_data_to_validate();
$this->validation_rules();
if($this->form_validation->run() == false){
$this->_errors = $this->form_validation->errors();
return false;
}
return true;
}
function save($validate = true){
if($validate && !$this->validate())
return false;
return $this->new_record() ? $this->insert() : $this->update();
}
}
<?php
class Field extends ActiveRecordModel {
var $id = null;
var $name = '';
var $code = '';
var $is_encrypted = 0;
var $type = "";
var $soft_delete = false;
var $dynamic_field = 1;
var $created_at = null;
var $updated_at = null;
static function types() {
return array(
"Boolean" => "Boolean",
"String" => "String",
"Integer" => "Integer",
"Float" => "Float",
"Date" => "Date",
"DateTime" => "DateTime"
);
}
static function timestampable() {
return true;
}
static function primary_key() {
return "id";
}
static function table_name() {
return "field";
}
static function class_name(){
return 'Field';
}
static function mapper() {
$fields = Field::all();
$result = [];
foreach($fields as $field)
$result[$field->id] = $field->code;
return $result;
}
function validation_rules(){
$code_uniqueness = $this->uniqueness_field('code');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', "trim|required|{$code_uniqueness}");
$this->form_validation->set_rules('type', 'Type', 'required');
}
}
CREATE TABLE `field` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`code` char(32) NOT NULL,
`type` char(24) NOT NULL,
`is_encrypted` tinyint(1) NOT NULL DEFAULT '0',
`soft_delete` int(11) NOT NULL DEFAULT '0',
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`dynamic_field` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `field`
ADD PRIMARY KEY (`id`);
<?php
class Scope extends ActiveRecordModel {
var $id = null;
var $name = '';
var $searchable_fields = array();
var $updatable_fields = array();
var $created_at = null;
var $updated_at = null;
static function timestampable() {
return true;
}
static function serialize_fields() {
return array('searchable_fields', 'updatable_fields');
}
static function primary_key() {
return "id";
}
static function table_name() {
return "scope";
}
static function class_name(){
return 'Scope';
}
function validation_rules(){
$code_uniqueness = $this->uniqueness_field('name');
$this->form_validation->set_rules('name', 'Name', "trim|required|{$code_uniqueness}");
}
}
CREATE TABLE `scope` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`searchable_fields` text NOT NULL,
`updatable_fields` text NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `scope`
--
ALTER TABLE `scope`
ADD PRIMARY KEY (`id`);
function seed_static_fields(){
$options = array(
array("name" => "pat_id", "code" => "pat_id", "type" => "String"),
array("name" => "pat_gender", "code" => "pat_gender", "type" => "Integer"),
array("name" => "pat_dob", "code" => "pat_dob", "type" => "Date"),
array("name" => "pat_age", "code" => "pat_age", "type" => "Integer" ),
array("name" => "date_create", "code" => "date_create", "type" => "DateTime" ),
array("name" => "pat_version", "code" => "pat_version", "type" => "String" ),
array("name" => "pat_register_site", "code" => "pat_register_site", "type" => "String" ),
array("name" => "new_pat_id", "code" => "new_pat_id", "type" => "String" ),
array("name" => "fingerprint_l1", "code" => "fingerprint_l1", "type" => "String" ),
array("name" => "fingerprint_l2", "code" => "fingerprint_l2", "type" => "String" ),
array("name" => "fingerprint_l3", "code" => "fingerprint_l3", "type" => "String" ),
array("name" => "fingerprint_l4", "code" => "fingerprint_l4", "type" => "String" ),
array("name" => "fingerprint_l5", "code" => "fingerprint_l5", "type" => "String" ),
array("name" => "fingerprint_r1", "code" => "fingerprint_r1", "type" => "String" ),
array("name" => "fingerprint_r2", "code" => "fingerprint_r2", "type" => "String" ),
array("name" => "fingerprint_r3", "code" => "fingerprint_r3", "type" => "String" ),
array("name" => "fingerprint_r4", "code" => "fingerprint_r4", "type" => "String" ),
array("name" => "fingerprint_r5", "code" => "fingerprint_r5", "type" => "String" )
);
foreach($options as $field_attrs) {
$field_attrs['dynamic_field'] = 0;
$field_attrs['is_encrypted'] = 0;
$field = Field::find_by(array("code" => $field_attrs["code"] ));
if($field)
$field->update_attributes($field_attrs);
else{
$field = new Field();
$field->set_attributes($field_attrs);
if(!$field->save()){
pirnt_r($field->get_errors());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment