【发布时间】:2012-02-28 00:41:50
【问题描述】:
最近几天我对 DDD(领域驱动设计)很感兴趣,但我无法弄清楚谁创建和验证实体的职责。我将打破这个问题以涵盖不同的场景。
常规实体(可能带有值对象)。作为示例,让我们以电子邮件标识的用户为例。我有一个 UserFactory,它接收一组数据(可能来自表单 POST),并返回一个新的 UserEntity。工厂是否应该验证数据的完整性(例如:作为电子邮件给出的字符串是真实的电子邮件,密码字段 1 和字段 2 中的密码匹配等)?工厂是否应该验证不存在这样的用户(我们不想使用相同的电子邮件注册两个用户)?如果是,它应该自己做还是使用 UserRepository?
-
聚合实体。假设我们有一个 Post 实体和 Comments 实体。我想获得所有 cmets 的 post 12,所以我做了类似的事情
$post = $postRepository->getById(12);
getById 应该如何实现?像这样:
public function getById($id) {
$postData = $this->magicFetchFromDB($id);
$comments = (new CommentRepository())->getForPost(12);
return new PostEntity($postData, $comments);
}
或者可能是负责懒惰创建其 cmets 的帖子,例如:
class PostEntity {
public function getComments() {
if(is_null($this->_comments)) $this->_comments = (new CommentRepository())->getForPost($this->_id);
return $this->_comments;
}
}
? 我在这里很迷茫,没有足够的信息与 PHP 中的 DDD 示例,所以任何帮助将不胜感激!
非常感谢, skwee。
【问题讨论】: