Designing a DataMapper for objects that sometimes need to aggregate other objects but not always
I have an object called student which maps to a student table. There is also a courses table, and user_courses table to assign students to courses. This student object can have many course objects, and therefore, with my Students DataMapper it will retrieve student objects and any course objects for the courses that the student is enrolled in. This works fine for the cases where I need all of this information, but in the cases where I only need to display the student name and last name, the retrieval of course objects is unnecessary. My question is, how should I design my dataMappers to acc开发者_StackOverflow社区ount for this? Should I have separate mappers for different levels of student objects, i.e. baseStudentObject with just the basic student info and then an extendedStudentObject which additionally includes the course objects? Or better to implement some sort of lazy loading solution? As always, all input is very much appreciated! Cheers.
I'd say it's a trade-off. Design-wise, the lazy loading route would be the best to take. You don't really want artificially different types of Student floating around, clogging up your domain model. Sure it's not the end of the world if you have a basic Student
and a StudentWithCourses
as a quick hack, but it could get messy fast. You might end up with a StudentWithContacts
, or StudentWithCoursesButNotContacts
, etc... you see my point, it's not really object-oriented design. With lazy loading you'll only have one Student entity in your model, which is closer to the real domain.
That said, it won't be entirely trivial to implement lazy loading. So if time is of the essence, go with the two classes. When you get time to refactor you can add the lazy loading.
(Or, of course, you can use an existing data mapping ORM such as Doctrine.)
精彩评论