我最初是在stackoverflow上为这个问题写这个答案的,但是我认为同样的答案也适用于这个问题。
Mathias Verraes的一篇文章在这里谈论您的问题。他谈到了将模型中的值对象与服务UI的概念分开。
当被问及是否将国家建模为实体或价值对象时,引用该文章:
将国家/地区建模为实体并将其存储在数据库中没有本质上的错误。但是在大多数情况下,这会使事情变得复杂。国家不经常改变。一个国家的名称更改时,实际上,从所有实际目的来看,它都是一个新国家。如果某个国家/地区不再存在,则不能简单地更改所有地址,因为该国家/地区可能已分为两个国家。
他提出了另一种方法来引入一个新概念,称为AvailableCountry
:
这些可用的国家/地区可以是数据库中的实体,JSON中的记录,甚至可以是代码中的硬编码列表。(这取决于企业是否希望通过UI轻松访问它们。)
<?php
final class Country
{
private $countryCode;
public function __construct($countryCode)
{
$this->countryCode = $countryCode;
}
public function __toString()
{
return $this->countryCode;
}
}
final class AvailableCountry
{
private $country;
private $name;
public function __construct(Country $country, $name)
{
$this->country = $country;
$this->name = $name;
}
/** @return Country */
public function getCountry()
{
return $this->country;
}
public function getName()
{
return $this->name;
}
}
final class AvailableCountryRepository
{
/** @return AvailableCountry[] */
public function findAll()
{
return [
'BE' => new AvailableCountry(new Country('BE'), 'Belgium'),
'FR' => new AvailableCountry(new Country('FR'), 'France'),
//...
];
}
/** @return AvailableCountry */
public function findByCountry(Country $country)
{
return $this->findAll()[(string) $country];
}
}
因此,似乎存在第三种解决方案,即将查找表建模为值对象和实体。
顺便说一句,请确保您在评论部分中查看有关该文章的认真讨论。