I am studying some OOP concepts and I see a lot about the SRP issue, "separate actions into classes etc". at the level of tests, I decided to create a small system to register users in order to test the knowledge, only that I came across some questions
1 - Should I separate the validation logic and the part of CRUD into classes separated?
2 - Is it the responsibility of the user to validate himself?
2.1 - Is the User class responsible for "accumulating" validation errors?
3 - Is the user responsible for saving himself?
4 - What would this example look like with thousands of attributes? use a loop in setter methods?
What I concluded, based on the studies:
- I want to use 3 classes, User, UserValidator and UserCRUD, because in my understanding they are different "actions" The user class would be the most "abstract", relating validation and integration with the database.
-
Should I create a second class called UserValidator that would be responsible for the validation rules and could be coupled to some validation library? (Respect / rakit)
-
And finally, I would create a last class called UserCRUD, which would inherit the methods of another class called "crudModel", responsible for database integration
Code sample:
class User {
private $name;
private $age;
function __construct () {
$this->userValidator = new userValidator;
$this->userCRUD = new userCRUD;
}
function setName($name) {
if($this->userValidator->validateName($name))
$this->name = $name;
}
function setAge($age) {
if($this->userValidator->validateAge($age))
$this->age = $age;
}
function hasErrors () {
return $this->userValidator->hasErrors();
}
function Save () {
$user_data['name'] = $this->name;
$user_data['age'] = $this->age;
return $this->userCRUD->create($user_data);
// retorna true para salvo e falso para erro
}
}
-
class UserValidator {
private $error_bag;
public function validateName ($name) {
if(strlen($name) > 5)
return 1;
else
$this->setValidationError('name', 'Nome deve ser maior que 5');
}
public function validateAge ($age) {
if(is_numeric($age))
return 1;
else
$this->setValidationError('age', 'Idade inválida');
}
private function setValidationError ($error, $error_msg) {
$this->error_bag[$error] = $error_msg;
}
private function getValidationErrors() {
return $this->error_bag;
}
public function hasErrors () {
if( empty($this->getValidationErrors()) )
return false;
else
return $this->getValidationErrors();
}
}
Code call:
$User = new User;
$User->setName('Fulano de Tal');
$User->setAge(50);
if($User->hasErrors()) {
// exibe os erros na tela
print_r($User->hasErrors());
} else {
// salve o usuario
$saveUser = $User->Save();
var_dump($saveUser);
}