Should input validation be done with a separate class, rather than in a DB write class? Or should it be a method of the writing class?
Eg. (shorthand version)
class DBWrite {
public function add($input) {
$data = new Validator($input);
if($data->isValid() == true) {
// write to DB
}
}
}
or would it be better to have the validation as part of the DBWrite class? Or would it be in too much of violation in terms with separation of concerns (or something else)?
class DBWrite {
public function add($input) {
if($this->inputIsValid() == true) {
// write to DB
}
}
private function inputIsValid() {
// Check that input is valid and return true if it is
}
}
Any other thoughts will also be appreciated, thanks!
If the Validator can be used in other classes than DBWrite, or if later you may want to swap out validators later, I’d go the route of separate Validator class and subclasses. You might also want to add a method to set/get your validator class in your DBWrite so you can swap out different validators at runtime.