Setting object data in an Active Record pattern, before sql commit
I am using the Active Record design pattern in my web app, and after looking at the code in my class that handles CRUD (create, read, update and delete) on a table in the DB, i'm wondering if there's a better way to set the data.
Let's say my table has around 15 columns, an开发者_运维技巧d my class has 15 member variables to represent the columns. I have a form which allows a user to input data for each of those variables, and on submit, my script reads everything from _POST and _GET and compiles it into an array called $params.
Currently my class setter methods looks like this:
public function setData($data1, $data2, $data3,...,$dataN-1){
$this->data1 = $data1;
$this->data2 = $data2;
$this->data3 = $data3;
...
$this->dataN-1 = $dataN-1;
}
I was wondering, what the problems would be if I changed the setData argument to be an array, specifically the array containing the _POST and _GET values, so something like this
public function setData($data){
$this->data1 = $data['data1'];
$this->data2 = $data['data2'];
$this->data3 = $data['data3'];
...
$this->dataN-1 = $data['dataN-1'];
}
Assume that all the form element names are correct. Obviously, the time will be saved when I call the method, not having to list 15 arguments. I am going to be using prepared statements for all INSERTs and UPDATEs. Are there any other pitfalls that I should be aware of doing this?
Thanks a lot for your help.
Why don't you use an array too for $this->data[] in your class?
You could this way use a foreach and could maintain/automatize it more easily, fetching data or setting it in your DB.
EDIT : this way you fill your array
in your class :
private $data = array(
'db_column_name_1' => null,
'db_column_name_2' => null,
'db_column_name_3' => null,
...
'db_column_name_n' => null
);
public function setData($data){
foreach ( $this->data as $key => $value )
$this->data[$key] = $data[$key] ;
}
Symmetrically you could as easily make the right INSERT/UPDATE query
精彩评论