From what I understand a DomainService should be implemented against a RepositoryInterface, so we could change with easy the repository (which its a part of the Infrastructure layer)

So, if I have:

class UserService{

    function __construct(UserRepository $rep){
        $this->rep = $rep;

    function createNewUser($attributes){
        return $this->rep->create($attributes)->persist();

It means, that in my ApplicationService (some call it Action) i would have:


class UserAplicationService{

    function create(UserCreateCommand $command){
        $service = new UserService(new UserRepoitory());


That means that every time I use my DomainService I have to instantiate my repository object. Doen't make this ApplicationServices to be coupled with Repository Implmentation?

Question: Where should I instantiate repository objects that are used in Domain Services?


Miško Hevery writes often about Dependency Injection. video

The usual answer is that you are going to instantiate your repository object when you connection your application to your persistence layer: ie, when you are assembling your object graph (in other words, during your initialization procedure, before you start processing requests).

UserRepository $repository = $frobozzMagicUserRepositoryFactory.create(...)
UserService $userService = new UserService($repository)
UserApplicationService $userApplicationService = new UserApplicationService($userService)
|improve this answer|||||
  • So your Controller (or wherever you call your ApplicationService will be called) will be aware of your Repositories? – user237329 May 26 '16 at 21:39
  • @user237329 No, the UserApplicationService only knows about UserService and uses its API, it has no idea that UserService may actually contain a repository. – Andy May 26 '16 at 22:03
  • I was asking abouy the Controller. I was looking at the example tha @VoiceOfUnreason gave. The last 3 lines – user237329 May 27 '16 at 5:32
  • I was following your question - if you put what you think the Controller looks like in your question, I'll try to match it in my answer. – VoiceOfUnreason May 27 '16 at 6:01
  • Your controllers are often automatically instantiated by frameworks and these frameworks usually support automatic dependency injection mechanisms. You want to register these dependencies with the injector and let the framework do the rest. – plalx May 30 '16 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.