Take the 2-minute tour ×

I am fairly new to Domain driven design but what I uderstand of it is that you speak to the application service, which is the entry to your "model". The service can talk to a repoistory which uses sources (files, databases, etc) to get data. The repository returns an entity.

That is the global idea what I get of it. THe service knows the repoistory but not the entity etc.

Now I have the following issue.

I have an entity user, which is something like the following (is just an example)

class User
    protected $name;
    protected $city_id;

    public function getCity()
         // return $city_entity;

The getCity() function returns the city entity. I wish for this function to use lazy loading so injecting the CityEntity when you use the user repository is not really lazy loading.

I came with two solutions to the problem. But I feel that both are against the DDD principals

First solution I came up with is to inject the city repository in the user entity, disadvantages: if you need more repositories you have to load them all in the entity. It looks like answer but it just looks like a wrapper for the repository to me. So why dont just inject the repository then

Second solution, you give the entity an service locator. The disadvantage of this is you dont know any more which repositories are needed unless you read the code.

So now the the question is. What is the best way to give the flexibility of lazy loading will keeping the ddd principals intact

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

One of main point in DDD is that your domain model should only express the ubiquitous language of the bounded context to handle the business rules.

Thus, in DDD entities, lazy loading is an anti-pattern. There are some reasons for that:

  1. if an aggregate holds only the data that it requires to ensure business invariants, it needs them all and they are few, thus eager loading works better.
  2. if you lazy load data, your clients have to handle much more exceptional paths that those relevant in business terms
  3. you can use shared identifiers to cope with references between aggregates
  4. it's cheap to use dedicated queries for projective purposes (often called read-model)

IMHO, you should never use DDD entities as a data access technique: use DTOs for that.

For further info you could take a look at Effective Aggregate Design by Vaughn Vernon.

share|improve this answer
add comment

Your Answer


