4

I am working on a team where my mates introduced the service & repository pattern. We work on Lumen micro framework. So from the controller, the call is passed to the service and then to the repository.

We use controller injection. The service and transformer are injected into the controller's constructor. The service has the repository instantiated in its constructor. We are to follow this rule:

Route -> Controller (Service & Transformer) -> Service(Repository) -> Repository(Model).

The values inside the parentheses mean that they will be initialized inside the constructor.

Now, sometimes it is required to use another repository from the current one. Suppose I am on posts and I need to call user. What would be the way to go? Some say we should inject the user repository into the current repository (post). I disagreed because I don't think we should instantiate the user repository when it is not needed. Rather I would pass the user repository from Controller -> Service -> Repository. Would that be right?

Code:

  • Without passing the repository forward: Paste 1
  • Passing repository to next: Paste 2
Martin Maat
  • 18,652
ssi-anik
  • 149

1 Answers1

1

I don't think that one repository should call another repository directly. Your service knows which repositories to deal with. So it would be clean if controllers deals with 2 services: UserService & PostService. It does something with UserService and then with PostService. Since Users and Posts are 2 different domains, it would be cleaner for them to live independently. This also lets you to decouple things. In future you may need few more repositories and you don't want to pollute your UserService with multiple repositories.

If you don't want different services, then I would inject UserRepsitory and PostsRepository to UserService thru dependency injection and let UserService take care of calling multiple repositories instead of one repository calling other repository.

Reading this would help: How accurate is "Business logic should be in a service, not in a model"?