I have a model and I want to validate some of its properties. I'm using getters and setters so I have these options:
I could validate the property directly in the setter method like so:
class Users extends Model
{
protected $email;
public function setEmail($email)
{
if(!$email = filter_var($email, FILTER_VALIDATE_EMAIL)){
throw new \InvalidArgumentException('The email is not valid');
}
$this->email = $email;
return $this;
}
}
or I could validate it in the validation method:
class Users extends Model
{
protected $email;
public function setEmail($email)
{
$this->email = $email;
return $this;
}
public function validation()
{
$validator = new Validation();
$validator->add('email', new \Phalcon\Validation\Validator\Email(
[
'message' => 'The e-mail is not valid'
]
))->add('email', new \Phalcon\Validation\Validator\PresenceOf(
[
'message' => 'The e-mail is required'
]
));
return $this->validate();
}
}
I understand that for some cases where a rule depends of mulitple fields, I have no choice but to validate in the validation() method, but as in the email example above I don't need to.
So I'm wondering if it's best to keep everything together in the validation() method, or try to keep the validation close to the property assignment.
The first example has the advantage that it won't allow the program to continue if the email is invalid, instead of going through all the assignments and then triggering the error.
The validation() method has the advantage of keeping all checks together, I guess?
What do you think?