Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repository pattern: Can a repository use other repositories?

Suppose I have a TeacherRepository that needs to make use of a CourseRepository per the code below. Teacher and Course form a many to many relationship. Teacher and Course do not form an aggregate. Would you consider this proper use of the pattern?

class TeacherRepository {

    @Inject(@Named("courseRepository"))
    private final CourseRepository courseRepository;

    public void addCourseToTeachers(String courseName) {

      Course course = courseRepository.findByName(courseName);

      for (Teacher teacher : readAll()) 
        teacher.addCourse(course);
    } 
}
like image 958
Chuck Stephanski Avatar asked Feb 15 '11 20:02

Chuck Stephanski


Video Answer


1 Answers

I don't think it is the task of the TeacherRepository to deal with courses. IMHO it would be better to handle this in a separate class. It is better to keep a single responsibility for every class.

Update

But if you absolutely want to add this functionality to TeacherRepository, you can do it without any dependency to CourseRepository:

class TeacherRepository {
  public void addCourseToTeachers(Course course) {

    for (Teacher teacher : readAll()) 
      teacher.addCourse(course);
  } 
}

...
CourseRepository courseRepository = ...;
TeacherRepository teacherRepository = ...;
...
Course course = courseRepository.findByName(courseName);

if (course != null)
  teacherRepository.addCourseToTeachers(course);
like image 76
Péter Török Avatar answered Nov 03 '22 19:11

Péter Török