Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single or multiple repository classes?

My database is relatively small, 8 tables, each with less than 5 columns. I use EF. I created single repository class, but now that I think it might not be the right way to use it. Should I have separate repository class for each of my controllers? Lets say I have Products, Users, Unicorns would it be fine to have a single repository class to operate with all of those and instantiate in each of those controllers, or should I create a separate repository class for each of those?

like image 869
m0s Avatar asked Jul 31 '11 06:07

m0s


2 Answers

One of the pivotal concepts of DDD is the aggregate root - this is the 'top level' entity through which you manage entire sets of related entities.

For example, in a retail scenario the 'Order' would be an aggregate root through which you could access the Order itself, a list of OrderItems (ie Product + Amount + modifiers such as discounts), BillingAddress, ShippingAddress and PaymentMethod. Each of those is closely related to the order itself, to the point where they have no reason to exist outside the scope of the order.

Each aggregate root should have a repository which owns the responsibility of persisting the entire subgraph of objects under the root. So in the above example, you would NOT want or need a repository for OrderItems which allows access to order items independently; instead you should implement a single OrdersRepository which deals with Orders and all their sub-components as a single unit.

Depending on your specific domain model you may need one or more repositories, but certainly not one per entity type. The key question to ask when looking for aggregate roots is "does this entity have its own identity and lifecycle?" Orders do, OrderItems don't.

like image 153
Addys Avatar answered Oct 26 '22 06:10

Addys


Think Domain-Driven Design, and with that in mind, you divide the logical structure of your project not as classes only, but as domains also, which means all operations have got to do with the Product are located within the ProductsController and consequently within the ProductsRepository, so I prefer many repositories each equipped with operations to deal with some aspect of your project.

Not all aspects may need a repository, but that is what you decide.

like image 35
Ken D Avatar answered Oct 26 '22 07:10

Ken D