Is it common and\or wise to write a generic insert function for a parent model that child models will inherit from? I am working with CodeIgniter\PHP on a very simple CRUD app but this question is really language\framework independent.
Inheriting a read function that reads(selects) one value works very well and feels right:
Parent Model
public function read($columnSelect,$columnCondition,$value) {
$query = "SELECT $columnSelect FROM $tableName WHERE $columConditionn=?";
$res = $this->db->query($query,$columnName);
if ($res->result()->num_rows()>0)
return $res->result();
else
return false;
this can allow you to retrieve user id’s , emails , check for existence of certain columns etc, definitely something I feel will be useful in most or all my models so it’s a good idea to write that function in the parent model. All the read functions that are more complicated will obviously be specific to each model (e.g queries that read more than one value etc)
Now what about insert? I can’t think of any generic insert besides writing functions to insert one value, two values etc or writing an ‘ugly’ function to will get an array of parameters and build the insert query according to the array, e.g:
public function genericInsert($columnList,$valueList) {
$query = " INSERT INTO $tableName(
//now code that parses columnList and adds ','
//and then code that adds VALUES(..) in the same manner
This definitely doesn’t feel like a “pattern” to me and feels wrong.
Am I overlooking something? What do you guys do for your inserts, is it specific to each model or do you try to figure a way to inherit from a parent model? And also, if you will, what are functions do you find yourself putting in your parent models? (updates,deletes etc)?
This is what my parent model looks like so far:
class MY_Model extends CI_Model {
public $tableName;
public function __construct($tableName) {
parent::__construct();
$this->tableName = $tableName;
}
public function read($columnSelect,$columnCondition,$value) {
$query = "SELECT $columnSelect FROM $tableName WHERE $columConditionn=?";
$res = $this->db->query($query,$columnName);
if ($res->result()->num_rows()>0)
return $res->result();
else
return false;
}
}
Hate answering my own question but this is what I was looking for
http://thephpcode.com/blog/codeigniter/a-smart-codeigniter-model