views:

93

answers:

3

Now I have an model User which represents an user in the application. And I use an UserRepository with methods like getById($id) and getAll().

An user can post reviews. If I want to show the 5 or 10 or maybe 20 last reviews of an user it's most logical to ask the user I think. So I would have a method $user->getLastReviews(5).

But what's the best way to implement this? Give each user an instance of the ReviewRepository (with a method $reviewRepository->getByUser(User $user) for example)? Or are there better ways?

+1  A: 

I think it's fine to have models contain and use instances of other models, so your way is fine, to have User model contain an instance of the Review model, and let that Review model handle the logic of getting said reviews.

Also, you could add a method to the UserRepository to handle it like so:

class UserRepository extends Model{
     $review = new reviewRepository();
     function getReviews($numOfReviews){
         return $this->review->getReviews($user_id);
     }
GSto
A: 

Another option would be to create a repository method where you passed in both variables. Something like $reviewRepository->getLastReviewsByUser(5, $user).

KevnRoberts
That is the option I used mostly until now idd. But then you call this method in your Controller I think? Then you don't have a direct relation in your domain models, but more an indirect.
Derk
A: 

Usually this is a job for the ORM. Almost every framework uses one implementation (ie. Doctrine for PHP/Symfony or Hibernate for Java) but naturally you can implement your own ORM (ORM are often implemented using introspection).

Once you have an ORM library you define relations between Models in a "setup phase" (in your case you'll have "user has many reviews"). Then you'll use the ORM methods which knows how to deal with those ones (often relations are mutual ie. "review belongs to user"). The concept is that this setup phase will discharge you from dealing with issues like the one you pointed.

My suggestion is to use one of the already existing ORM implementations which already supplies facilities for getter and setter methods of related Models. In the other case, you have to write specialized getters and setters by yourself for every Model.

gpilotino
Thanks for your answer. I know about ORM's, but ORM's have also disadvantages. If performance is an option and you want to use the full power of a database a general ORM is not the best option.
Derk
i think you're already writing a simple ORM when you begin to code your getter methods (ie. $user->getLastReviews). some ORM are very lightweight (the Kohana one it's a couple of php files) and the performance cost is negligibile vs the advantages of code reusing and easy maintenability.
gpilotino