Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregates and Repository. How to determine aggregates?

Tags:

I have recently been looking at the Repository Pattern as a way of brushing all the details of persistence under the carpet where the client code is concerned. While reading around it appears that a Repository is/can be [usually?] responsible for aggregates rather than just straight-forward classes.

This make sense to me as you could have a class defining Posts and another defining Comments. This makes an ideal candidate for an aggregate since the two are very closely related. However, how would I represent a Users class and its relationship with his or her Posts?

Would it make sense to aggregate Users with the Posts/Comments aggregate, or keep Users by itself and simply have an association via a good old fashioned reference?

I have tried looking for the answer myself using Google, but a lot of the examples I find are just stand-alone. ie, Posts/Comment or maybe Order and OrderLine etc. I can't find anything that shows how other related classes fit together.

I am not applying this to anything specific, though PHP or Java/C# would probably be the area I would look to using these ideas. In any case I am just exploring and trying to get my head around some of these ideas and concepts before I run off and create a monster. :)

Thank you for your time.

like image 713
Etzeitet Avatar asked Aug 04 '09 03:08

Etzeitet


1 Answers

The Repository Pattern is fairly loosely defined and does not necessarily have any relationship to the Aggregate Pattern. However, if you subscribe to the DDD way of doing things, then yes, repositories are unique to aggregates.

So let's have a look at this from the DDD point of view. DDD says that objects within an aggregate can have a reference to another aggregate root, but objects within an aggregate can only be accessed via the root. The rule of thumb for determining aggregates is what should be deleted when deleting the root. However, DDD discourages the use of relationships more than most methodologies saying that just because a relationship exists in a domain, it does not need to exist in your model of the domain, so just keep that in mind.

In your case, when you delete a post I assume that you would also delete the comments, but not the user who created the post or users who commented on it. Therefore, you are correct in defining the post/comment aggregate, but it would not make sense to group users into that aggregate.

Users, being its own aggregate, can contain a relationship to all of their posts, because Post is the aggregate root. You could also implement this a method on the PostRepository to get all of the posts by a given user. Hope that helps!

like image 111
Stefan Moser Avatar answered Oct 05 '22 14:10

Stefan Moser