我正在尝试实现Repository模式,以将我的Domain Objects与持久层分开。关于如何正确构建域对象,我有几个问题。
获取此示例域对象类:
class EmailSubscriberDomain
{
private $id;
private $first_name;
private $last_name;
private $company;
private $email;
public function __construct($id = null, $first_name, $last_name, $company, $email)
{
if ($id) {
$this->setId($id);
}
$this->setFirstName($first_name);
$this->setLastName($last_name);
$this->setCompany($company);
$this->setEmail($email);
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
if ($id = filter_var($id, FILTER_VALIDATE_INT)) {
$this->id = $id;
return true;
}
throw new Exception('ID value is null');
}
public function getFirstName()
{
return $this->first_name;
}
public function setFirstName($first_name)
{
if ($first_name) {
$this->first_name = filter_var($first_name, FILTER_SANITIZE_STRING);
return true;
}
throw new Exception('First name value is null');
}
public function getLastName()
{
return $this->first_name;
}
public function setLastName($last_name)
{
if ($last_name) {
$this->last_name = filter_var($last_name, FILTER_SANITIZE_STRING);
return true;
}
throw new Exception('Last name value is null');
}
public function getCompany()
{
return $this->company;
}
public function setCompany($company)
{
if ($company) {
$this->company = filter_var($company, FILTER_SANITIZE_STRING);
return true;
}
throw new Exception('Company value is null');
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
if ($email) {
if ($email = filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->email = $email;
return true;
}
}
throw new Exception('Email address value is null');
}
}
以下是我的问题:
在构造函数方面,此类是否正确设置?在实例化时填充域对象是好还是坏?
样本类中的验证是否过度杀伤?在传递到Repository's Factory之前,数据也将由表单验证库验证,该工厂将创建上面的对象并将(已经验证的)数据注入构造函数。我认为当数据来自另一端(持久层)时强制执行有效数据可能会有用,但是,这又是一个问题吗?
使用最初可能不可用的值(如上例中的ID)设置参数,以使处理这种情况的适当方式为空?这样,如果从表单数据创建对象时不存在该值,则对象实例化不会导致挂起,并且ID值尚不存在,但是当从持久性机制中提取数据时它也应该起作用,将提供身份证件。