Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification in dealing with collections with the repository pattern

If you have two repositories dealing with persistance to a relational DB, a personrepository that deals with "Person" objects, and an addressrepository which deals with "Address" objects, and a person object has a collection of addresses (probably lazy loaded). Obviously the personrepository would be used to persist changes to the person objects and addressrepository would be used to persist changes to the address objects, but what would be responsible for persisting changes to a persons address collection?

What strategies are available for persisting modifications to a person objects address collection back to the database? And where would that responsibility lie in the repositories(would it be the personrepository even though in the db it would be the addresses that stored the link to a person)?

I should mention that this is not using an ORM.

Thanks for any assistance, any strategies/clarification would be appreciated.

like image 911
gmn Avatar asked Feb 26 '23 09:02

gmn


1 Answers

A bit food for thought:

There are really two questions you need to answer before you decide how to address the problem:

  1. Can an Address exist without a Person?
  2. Can an Address be owned by more than one Person?

If the answer to 1. is no and the answer to 2. is no - you shouldn't have an AddressRepository and Person should be responsible for saving the Addresses in a normal 1-to-many relationship with a foreign-key in the Address. Otherwise, Person is suddenly responsible for deleting Addresses - or needs a reference to the AddressRepository - which IMO would end in a terrible mess of responsebilities.

If the answer to 1. is no and the answer to 2. is yes - you have a many-to-many relationship and Person should maintain this many-to-many relationship (as that is the only one with the knowledge needed to persist it).

If the answer to 1. is yes and the answer to 2. is no - Address should be responsible for updating the relationship - and should have a Partner property, so the association in the objects is uni-directional.

And lastly - if both are yes - You again have a many-to-many relationship, but this time it would be more reasonable to let the Address handle the many-to-many association.

I hope this helps you decide :)

like image 150
Goblin Avatar answered Apr 25 '23 05:04

Goblin