3

I am fairly new to Domain Driven Design (DDD), but what I understand of it is that you speak to the application service, which is the entry to your "model". The service can talk to a repository 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 repository 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)

<?php    
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, which has 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 not just inject the repository then?

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

So now, the question is, what is the best way to give the flexibility of lazy loading while keeping the DDD principals intact?

Community
  • 1
  • 1
MKroeders
  • 7,562
  • 4
  • 24
  • 39

1 Answers1

15

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.

Community
  • 1
  • 1
Giacomo Tesio
  • 7,144
  • 3
  • 31
  • 48