I understand that the repository pattern abstracts the persistence of domain objects, allowing a developer to read/write/delete objects from persistent storage without knowing how the object is stored (SQL, NoSQL, flat files, etc). I'm quite fond of the repository pattern and find it works well in many situtations, e.g., abstracting the business logic from the persistence logic, allowing lazy-loading of objects where appropriate, etc.
However, what I'm not clear on is whether or not the repository object maintains a reference to all objects or not? For example:
Repository repository;
std::shared_ptr<Person> pPerson = repository.retrievePersonById("bob");
p->updateDetails("Bob", "the Builder");
repository.savePerson(p);
- In the above hypothetical C++ example, should
repository
maintain a reference to thePerson
instance returned? Yes - thanks Guillaume31 for your in-memory analogy. - If the answer to Q1 is "yes", when and how should
repository
remove that instance ofPerson
? Presumably this is when the reference count reaches zero. - If the answer to Q1 is "no", how do you handle situations when another area of wants access to the same object, but because
repository
no longer stores an internal reference to it, it hydrates a fresh copy from the database, and you effectively have two instances ofPerson
when you really should be referring to the same instance? Given that the answer to Q1 was "Yes", then the repository always maintains a reference and so should always return the same object.
I'm actually writing a PHP application, despite the fact that the above example is in C++.