问题
Say I've got two simple entities: User and Review. How bad is it if User calls the Review repository? What is the "clean" way for the User to get its Reviews?
class User
{
public function getReviews()
{
return reviewRepository.findByUser(this);
}
}
I did have a look at this question, but although they say this is a bad practice, I didn't find an answer there.
回答1:
The clean way in DDD is to have the UserRepository fill the reviews of the User when asking for a User.
class UserRepository
{
public User GetUserByID(long userId)
{
var user = CreateUser();
user.Reviews = FindReviewsforUser(userID);
return user;
}
}
But before you do this, you need to verify that your User Entity in your Domain is also an AggregateRoot! Only AggregateRoots have Repositories. Please take a look at this question to see or get some insights to the problems while desiging aggregateroots.
来源:https://stackoverflow.com/questions/6793047/can-an-entity-access-a-repository