我正在使用 DDD 重构一个项目,但我担心不要让太多实体成为自己的聚合根。
我有一个Store
,它有一个ProductOption
s 列表和一个Product
s 列表。AProductOption
可以被几个Product
s 使用。这些实体似乎Store
非常适合总体。
然后我有一个Order
,它暂时使用 aProduct
来构建它OrderLine
的 s:
class Order {
// ...
public function addOrderLine(Product $product, $quantity) {
$orderLine = new OrderLine($product, $quantity);
$this->orderLines->add($orderLine);
}
}
class OrderLine {
// ...
public function __construct(Product $product, $quantity) {
$this->productName = $product->getName();
$this->basePrice = $product->getPrice();
$this->quantity = $quantity;
}
}
目前看来,DDD 规则受到尊重。但我想添加一个要求,这可能会违反聚合规则:商店所有者有时需要检查包含特定产品的订单的统计信息。
这意味着基本上,我们需要在 OrderLine 中保留对 Product 的引用,但这绝不会被实体内的任何方法使用。在查询数据库时,我们只会将此信息用于报告目的;因此,由于此内部引用,不可能“破坏” Store 聚合中的任何内容:
class OrderLine {
// ...
public function __construct(Product $product, $quantity) {
$this->productName = $product->getName();
$this->basePrice = $product->getPrice();
$this->quantity = $quantity;
// store this information, but don't use it in any method
$this->product = $product;
}
}
这个简单的要求是否要求 Product 成为聚合根?这也将级联到 ProductOption 成为聚合根,因为 Product 对它有引用,因此导致两个聚合在 Store 之外没有任何意义,并且不需要任何存储库;我觉得很奇怪。
欢迎任何评论!