Search code examples
ormrepositoryentityrepository-patternddd-repositories

Can an Entity access a Repository?


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.


Solution

  • 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.