Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Domain-driven design pattern - accessing repository from domain

I've been working on applying the domain-driven design pattern to our web application. One of the issues we've ran into is avoiding having to use a repository from within an entity.

For example, we have some entities whose methods will trigger an email. So we have to have access to the email template (stored in the database), as well as create a new email record in the database queue table. We are currently violating the pattern by accessing the repositories in these instances.

Should we be utilizing a "service" or "application" layer in these instances (we have lots of them)? Is there a better way to get around this issue?

like image 807
Shane N Avatar asked Mar 07 '11 18:03

Shane N


People also ask

Can domain services access repository?

Yes, a domain service can access repositories.

What is repository in Domain-Driven Design?

Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.

Is repository part of domain?

Yes, repository implementations can definitely be a part of your domain model.

Which of approach we can use for Domain-Driven Design?

Domain-Driven Design is a concept introduced by a programmer Eric Evans in 2004 in his book Domain-Driven Design: Tackling Complexity in Heart of Software. It is an approach for architecting software design by looking at software in top-down approach.


1 Answers

Yes, I would recommend creating a service to perform the sending of the email. You can create an interface for interacting with the service in the same project as the domain model, but provide the implementation of the service in a separate project so that there is no hard dependency from the model to the service. The dependency is reversed - from service to model. This also creates a better setup for implementing unit tests to ensure that your service is called under the cirucmstances that it should be since you'll now be able to mock the service in your unit tests.

The one thing that is left to do is make sure that your service is injected any time one of these object types is created. So, you'll defer object creation either to the repository. Or even better, use a dependency injection framework to resolve the dependency for you.

like image 89
carmbrester Avatar answered Oct 05 '22 23:10

carmbrester