I would like to have a custom function to insert/edit/delete records from a database without
having to write the single queries for each page.
I have thought to proceed like this:
//page.php:
$datainput = new DataInputAbstraction();
$datainput->setTableName = 'portal';
$datainput->setAllowedFields = array('name'=>'defaultvalue','text'=>'','desc'=>'');
$datainput->run();
// DataInputAbstraction.class.php:
class DataInputAbstraction{
//> attr
public function run(){
if (isset($_POST['action']) && $_POST['action']=='insert') {
$filteredData = array_intersect_key($this->allowedFields,$_POST);
//> Do a mysql query to insert $filteredData to $this->table
}
//> Do other stuff if $_POST['action'] == 'edit' | 'del'
}
}
basically the method run() performs the right action based on $_POST[‘action’].
Filters unwanted variables present with doing an intersect_key with the attribute allowedFileds, after that it builds the query to
INSERT INTO $this->tableName (array_keys($field)) VALUES (array_values($field)) (pseudocode)
Do you think this is a good way to proceed? There are better way or does php offers a similar built-in functionality?
Thanks
In my opinion, if you don’t want to use something that is already out there (RedBean is a really nice choice BTW), then you would be good to proceed about this.
I always prefer as much abstraction as possible because it keeps you from making hard decisions about what service to use. For example, you will create a data abstraction layer to handle all your data transactions that way if you change database providers later on the only thing you have to recode is your data abstraction class.
So, I think it’s a good idea. My only recommendation would be to make sure you adhere to DRY principals and keep your abstraction layer very modular. The code that uses the abstraction layer shouldn’t know anything about how it works, just that it provides the data needed.
Hope that helps.