I'm interested in DDD (Domain Driven Design) in the last days, but I can't figure out the responsibilities of who creates and validates the entities. Ill break this questions to cover different scenarios.
Regular entity (Possibly with value object). As an example lets take a user who is identified by Email. I have a UserFactory that receives an array of data (possibly from form POST), and return me a new UserEntity. Should the factory validate the integrity of the data (ex: string given as Email is a real email, passwords in password field 1 and field2 match and etc)? Should the factory validate that no such user exists already (we dont want to register two users with the same email)? If yes should it do it my itself or using the UserRepository?
Aggregate entity. Lets assume we have a Post entity and Comments entities. I want to get post 12 with all its comments, so I do something like
$post = $postRepository->getById(12);
How getById should be implemented? like this:
public function getById($id) {
$postData = $this->magicFetchFromDB($id);
$comments = (new CommentRepository())->getForPost(12);
return new PostEntity($postData, $comments);
}
Or maybe the post responsible for lazy creating its comments, something like:
class PostEntity {
public function getComments() {
if(is_null($this->_comments)) $this->_comments = (new CommentRepository())->getForPost($this->_id);
return $this->_comments;
}
}
? I'm very lost here and there is not enough information with examples for DDD in PHP, so any help will be appreciated!
Thank you a lot, skwee.