Search code examples
domain-driven-designrepository-patternddd-repositories

PHP How should Repositories handle adding/removing/saving/deleting entities?


I am having a bit of trouble implementing the Repository pattern, due to some confusion.

As far as I can tell now, a Repository should behave like an in-memory collection of objects, so if I do say:

$users = new UserRepository(new UserMapper);
$users->findAll();

The Users repository will load and return an array of User entities. Now I can either use them for just reading data, or can update the data on any particular entity, and invoke a save() method on the Repository that will utilize the Mapper to save the loaded entities back to the data source, with the updates that have been applied.

What I am wondering is if that is a correct understanding.

Should the add() method add an entity directly to the data source, or only to the collection within the Repository?

Likewise for remove(); should this method remove an entity from the data source, or only from the Repository.

The confusion stems from the fact that some implementations I have seen in tutorials have both add()/remove() methods, alongside save()/delete() methods. Is that the correct approach?


Solution

  • I've been developing using DDD techniques for around 6 months now and always use the save and delete methods, the save should persist the data to your persistence layer, the delete should remove from your persistence layer.

    Saying the above, there is no reason why it shouldnt add to your collection.

    p.s check out the dddinphp Google Group, theres an active community purely for these questions