Skip to content

Instantly share code, notes, and snippets.

@jpalala
Forked from Eclarian/db_driver_extension.php
Created November 16, 2011 08:15
Show Gist options
  • Save jpalala/1369553 to your computer and use it in GitHub Desktop.
Save jpalala/1369553 to your computer and use it in GitHub Desktop.
CodeIgniter Database Driver Extension to simplify the CRUD actions within your app
<?php
/**
* Database Driver Extension
*
* DEPENDENCIES:
* CodeIgniter 2.x.x (with ActiveRecord turned on)
* is_associative() function -- place in autoloaded helper file. It should load early enough before any queries.
*
* This Extension allows you to insert/update, batch insert/batch update, and delete from any
* table within your database simply with an easy interface
*
* --------------------------------------------------------------------------
*
* REASONS:
* I found myself writing a ton of simple CRUD functions in my model
* that did nothing special with the data except for insert, update, or delete.
* So I dropped in this little magic method in my ./system/database/DB_driver.php file
*
* This will shrink down the size of your model without adding any additional bloat to your controllers.
*
* In case you don't know what the __call() function does, it will be triggered anytime
* you attempt to invoke an inaccessible method within an object's context.
* @example $this->db->inaccessible_method()
*
* CONVENTION:
* You must separate the key word from the table name with an underscore
* The table name is fetched from the second section of the function name after the keyword (either save_* or delete_*)
*
* --------------------------------------------------------------------------
*
* PARAMETER EXPLANATION:
* It is important to note that the method will function BASED on the parameters passed.
* It functions implicitly rather than explicitly. Below I'll list the number of parameters
* after the db method. It will determine whether or not to do single or batch functionality based on data.
*
* + Insert/Batch Insert (one parameter) - array of data to insert into DB
* 1. (array) Data to be Inserted
* + Update/Batch Update (two parameters required, one optional)
* 1. (array) Data to be Updated
* 2. (array|string) Conditions for update query.
* If it is an update batch, you must use a string that corresponds to the field
* which will be used as the condition within the query.
* 3. [optional] (bool) If resource does not exist then insert it. This won't work
* perfectly on batch updates as there could be some that exist and others that don't
* + Delete (one parameter required)
* 1. (array) Conditions
*
* --------------------------------------------------------------------------
*
* USAGE:
* + Insert/Batch Insert
* $data = array('field_name' => 'value', 'field_name2' => 'value'); // INSERT
* $data = array(array('field_name' => 'value', 'field_name2' => 'value'), ...); // BATCH INSERT
*
* $this->db->save_table_name($data); // Runs the Insert
*
* + Update/Batch Update
* $data = array('field_name' => 'value', 'field_name2' => 'value'); // UPDATE
* $cond = array('status' => '3'); // UPDATE
*
* $data = array( array('field_name' => 'value', 'field_name2' => 'value'), ...); // BATCH UPDATE
* $cond = 'field_name2'; // BATCH UPDATE
*
* $this->db->save_table_name($data, $cond); // Updates
* $this->db->save_table_name($data, $cond, TRUE); // Updates and Inserts if does not exist
*
* + Delete
* $this->db->delete_table_name(array('status' => '3')); // Deletes everything FROM table_name WHERE status = 3
*
* --------------------------------------------------------------------------
*
* I know this won't be for everyone, but it works amazing for me.
* Tell me if you have any suggestions for improvement!
*
* @author Joel Kallman, Eclarian LLC
* @copyright Copyright (c) 2011, Eclarian LLC
* @license MIT
*/
public function __call($name, $args)
{
// NO DATA PASSED
if(isset($args[0]) && empty($args[0]))
{
return FALSE;
}
// Load Singleton
$CI =& get_instance();
// Get Table and Function Call
$table = explode('_', $name);
$run = array_shift($table);
$table = implode('_', $table); // Rejoin Table
// Process Arguments
$num_args = count($args);
$is_assoc = (int) is_associative($args[0]);
// Check if Has Third Param
if($num_args === 3 && $args[2] === TRUE)
{
// Default for Update
$num_args = 2;
unset($args[2]);
// Setup for Insert If No Record Exists for Update
if(0 === $CI->db->from($table)->where($args[1])->count_all_results())
{
$num_args = 1;
unset($args[1]);
}
}
// Prepare Args for call_user_func_array
array_unshift($args, $table);
// Method Map to Name >> Based on __call($name), num of args, and whether is_assoc
$method = array(
'delete' => array(
1 => array('delete','delete')
),
'save' => array(
1 => array('insert_batch', 'insert'),
2 => array('update_batch', 'update')
)
);
if(isset($method[$run][$num_args][$is_assoc]))
{
call_user_func_array(array($CI->db, $method[$run][$num_args][$is_assoc]), $args);
return ($CI->db->affected_rows() > 0); // Boolean
}
return FALSE;
}
// --------------------------------------------------------------------------
/**
* Is Associative
*
* @param array
* @return bool
*/
function is_associative($array)
{
return (is_array($array)) ? (( ! is_int(key($array))) ? TRUE: FALSE): FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment