Search code examples
dependency-injectionrefactoringdomain-driven-designaggregationddd-repositories

Domain service with too many repositories


I have 4 related entities:

District (id, name, municipality, zip_code) Municipality (id, name, city) City (id, name, province) Province (id, name)

And I just made a domain service to get all data related to a Zip code. I need to find Districts, Municipality, City and Province related to it. So I'm injecting those 4 repos in my service. I read data from every repository, format it to (id, name) because is all the data that I need from them.

I think that there is violation of SRP, but can't find a way to do this in a better way. I have read already Refactor to Facade Service but don't think that this apply to my problem.

My questions are: 1. Should I put all those entities into an aggregation? 2. Where should be done data formating? In service in repo or another class called from service? 3. Any other better solution?

Thanks in advance


Solution

  • As you discovered, one repository per domain entity does not scale well. It's basically ignoring the relations between the entities.

    In ddd there is a concept of an aggregate root(ar) object which is basically a master node object with associated child objects. Different domain contexts will have different ars. Functionality is usually designed around ars as opposed to individual entities.

    So think in terms of having a repository support what is needed for a given ar. That means being able to do one zip code query and returning an ar consisting of a zip code root and attached districts, cities etc.

    To implement you will probably need a master object containing all the individual entity database mappings as well as their relations. Again, it's the relations that are important. Each repository will have access to the complete mapping information.

    You did not mention a language but in php here an example of an object relational manager that follows these concepts: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/