我想将 an 建模Address
为值对象。因为让它不可变是一个好习惯,所以我选择不提供任何设置器,这可能允许以后修改它。
一种常见的方法是将数据传递给构造函数;但是,当值对象非常大时,它可能会变得非常臃肿:
class Address {
public function __construct(
Point $location,
$houseNumber,
$streetName,
$postcode,
$poBox,
$city,
$region,
$country) {
// ...
}
}
另一种方法是将参数作为数组提供,从而产生一个干净的构造函数,但这可能会弄乱构造函数的实现:
class Address {
public function __construct(array $parts) {
if (! isset($parts['location']) || ! $location instanceof Point) {
throw new Exception('The location is required');
}
$this->location = $location;
// ...
if (isset($parts['poBox'])) {
$this->poBox = $parts['poBox'];
}
// ...
}
}
这对我来说也有点不自然。
关于如何正确实现一个相当大的价值对象的任何建议?