Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should repositories have update/save/delete methods?

I want to implement Repository design pattern for my project but it's not clear to use CRUD operations in repositories or not. Some resources say you shouldn't use update/save/delete methods because the repository is only for saving objects in memory and you should services for other actions.

Which one is the best way?

Thanks.

like image 777
Koray Küpe Avatar asked Feb 08 '18 10:02

Koray Küpe


People also ask

Should a repository have save?

Persistence-oriented repositories are aware that an object needs to be explicitly “saved” after any changes, so you can call the entity. save() method when an object is created or modified.

What should a repository contain?

The repository would contain all CRUD operations to be performed on the database, accepting and returning business layer entities. This means that the repository will reside in the business layer, because only the business layer can reference the data layer, not the other way round.

Should repositories return Dtos?

In most cases, it suffices to have a single entity-DTO conversion, which tends to happen in the business layer (BLL), which is one layer above the repository layer (DAL). In that sense, your repositories should not return a DTO.

Should I use repository pattern?

The Repository pattern makes it easier to test your application logic. The Repository pattern allows you to easily test your application with unit tests. Remember that unit tests only test your code, not infrastructure, so the repository abstractions make it easier to achieve that goal.


1 Answers

A summary of Martin Fowler’s definition of the Repository pattern:

Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.

So if we have both add and update methods, I could claim it’s not a collection-like interface, right? I shouldn’t need to bother checking if an object’s already there when adding to a set-like collection.

There are two common approaches about add/update:

  • Collection-oriented repositories try to mimic an in-memory collection, so you shouldn’t need to re-add an object if it was updated and already in the collection. The repository (or layers hidden below it, such as an ORM) should handle the changes to an entity and track them. You just add an object when you first create it and then no more methods are needed after the entity is changed.

  • Persistence-oriented repositories are aware that an object needs to be explicitly “saved” after any changes, so you can call the entity.save() method when an object is created or modified.

(Those are my interpretations of the definitions by Vaughn Vernon in Implementing Domain-Driven Design.)

delete is fine, but perhaps remove would be a better name.

like image 133
Eduardo Dobay Avatar answered Oct 11 '22 16:10

Eduardo Dobay