Currently, I create an object and use its setters to set the get/post data received from client. And call the validate() before calling the save() function like this:
//member registration
$m=new Member();
$m->setName($_POST['name']);
$m->setBirthDate($_POST['birthdate']);
$m->setAddress($_POST['address']);
$arrOfErrMsgs=$m->validate();
if(!empty($arrOfErrMsgs)){
//echo some error messages to client or redirect to a page that shows the error
exit();
}
$saveSuccess=$m->save(); //to be safe, inside this save function, it will also call validate() again before saving, so that even someone forgot to call validate() before calling save() by mistake, no dirty data will appear in the database
if($saveSuccess){
//echo a success message to client or redirect to a success page
}else{
//echo save failed message to client (normally this should not happen unless db server suddenly fails)
}
exit();
While this works, but there should be some alternatives. For example, maybe some of the validations can be done in the setters.
I would like to know what patterns for validation in model in PHP are the most common?