Validation and Error Generation when using the Data Mapper Pattern
Posted
by
AndyPerlitch
on Programmers
See other posts from Programmers
or by AndyPerlitch
Published on 2012-10-12T21:29:58Z
Indexed on
2012/10/15
3:52 UTC
Read the original article
Hit count: 223
I am working on saving state of an object to a database using the data mapper pattern, but I am looking for suggestions/guidance on the validation and error message generation step (step 4 below). Here are the general steps as I see them for doing this:
(1) The data mapper is used to get current info (assoc array) about the object
in db:
+=====================================================+
| person_id | name | favorite_color | age |
+=====================================================+
| 1 | Andy | Green | 24 |
+-----------------------------------------------------+
mapper returns associative array, eg. Person_Mapper::getPersonById($id) :
$person_row = array(
'person_id' => 1,
'name' => 'Andy',
'favorite_color' => 'Green',
'age' => '24',
);
(2) the Person object constructor takes this array as an argument, populating its fields.
class Person {
protected $person_id;
protected $name;
protected $favorite_color;
protected $age;
function __construct(array $person_row)
{
$this->person_id = $person_row['person_id'];
$this->name = $person_row['name'];
$this->favorite_color = $person_row['favorite_color'];
$this->age = $person_row['age'];
}
// getters and setters...
public function toArray()
{
return array(
'person_id' => $this->person_id,
'name' => $this->name,
'favorite_color' => $this->favorite_color,
'age' => $this->age,
);
}
}
(3a) (GET request) Inputs of an HTML form that is used to change info about the person is populated using Person::getters
<form>
<input type="text" name="name" value="<?=$person->getName()?>" />
<input type="text" name="favorite_color" value="<?=$person->getFavColor()?>" />
<input type="text" name="age" value="<?=$person->getAge()?>" />
</form>
(3b) (POST request) Person object is altered with the POST data using Person::setters
$person->setName($_POST['name']);
$person->setFavColor($_POST['favorite_color']);
$person->setAge($_POST['age']);
*(4) Validation and error message generation on a per-field basis
- Should this take place in the person object or the person mapper object?
- Should data be validated BEFORE being placed into fields of the person object?
(5) Data mapper saves the person object (updates row in the database):
$person_mapper->savePerson($person);
// the savePerson method uses $person->toArray()
// to get data in a more digestible format for the
// db gateway used by person_mapper
Any guidance, suggestions, criticism, or name-calling would be greatly appreciated.
© Programmers or respective owner