【发布时间】:2014-04-25 10:29:46
【问题描述】:
我有 1 个 Employee 实体,它拥有一个 ContactInformation 的值对象:
Employee.php
class Employee {
private $contactInformation;
public function __construct(ContactInformation $contactInformation) {
$this->contactInformation = $contactInformation;
}
public function getContactInformation() {
return $this->contactInformation;
}
}
ContactInformation.php
class ContactInformation {
private $email; // Required
private $cellPhone; // Required
private $phone; // Optional
private $address; // Optional
public function __construct($email, $cellPhone) {
$this->email = $email;
$this->cellphone = $cellphone;
}
/** Here goes a bunch of setter getter for those properties **/
}
如果员工的手机换了,岂不是更好吗
$employee->getContactInformation()->setPhone($newPhone)
而不是强制诸如
之类的不变性$employee->setContactInformation(new ContactInformation(/** 复制粘贴 这里**/));
根据 Eric Evans 的书,我了解到,当您更改值对象的一部分时,它与之前的值对象完全不同。
对于像这个 ContactInformation 这样稍微复杂一点的对象,我无法得出相同的结论,它应该是一个实体吗?
需要建议,谢谢!
【问题讨论】:
-
我会选择第一种方法,很少有第二种更好的情况。
-
@RoyalBg 我也是,但我就是无法摆脱这种关于如何将 ContactInformation 视为实体的恶心感觉
-
为什么不使用 ContactInformation 扩展 Employee 并允许 $employee->setPhone()?
-
@VincentNikkelen 这听起来有点奇怪.. 几乎就像说 Employee 对我来说是一个 ContactInformation
-
@SamuelAdam 对我来说,员工最好不要依赖联系信息,反之亦然。您不能单独拥有联系信息,因为它应该绑定到某个员工
标签: php oop domain-driven-design