【发布时间】:2023-03-03 13:15:01
【问题描述】:
我正在使用 DDD 重构一个项目,但我担心不会让太多实体成为自己的聚合根。
我有一个Store,它有一个ProductOptions 的列表和一个Products 的列表。一个ProductOption 可以被多个Products 使用。这些实体似乎非常适合 Store 聚合。
然后我有一个Order,它暂时使用Product 来构建它的OrderLines:
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 之外没有任何意义,并且不需要任何存储库;我觉得很奇怪。
欢迎评论!
【问题讨论】:
标签: domain-driven-design entity-relationship aggregate ddd-repositories aggregateroot