我应该在设置域对象属性时验证它们吗?
在这个例子中,我从我的模型层获得了一个用户域对象,目前只是在设置属性之前验证传入参数的类型和/或格式,因为我不知道应该验证什么域对象。一些例子可以帮助我理解它。
这是我应该如何验证域对象属性还是根本不应该验证它们?
在后一种情况下,我可以删除每个 setter 和 getter,并将域对象属性公开,这样我就可以直接与它们交互。
class User
{
private $id;
private $firstname;
private $lastname;
private $email;
private $password;
private $registerDate;
public function setId($id)
{
if (is_int($id)) {
$this->id = $id;
} else {
throw new Exception('Parameter must be an integer.');
}
}
public function setFirstname($firstname)
{
if (is_string($firstname)) {
$this->firstname = $firstname;
} else {
throw new Exception('Parameter must be a string.');
}
}
//{ etc setters }
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
}