Question

I'm trying to understand the concept of 'aggregate root'.

One of the things that confuses me is that I should not access a child entity directly without accessing its aggregate root. For example, let's say I have a computer entity and a hardware entity.

As far as I understand, I should not directly access a hardware entity directly. I should access a hardware entity through its aggregate root, which is a computer entity.

Let's say I have a controller that uses a repository and queries a computer entity.

class Controller_Test {

    public function loadHardware($computerRepository)
    {
        $computer = $computerRepository->find_by_id(1);
        $hardware = $computer->hardware; // lazy load
    }
}

If I'm using a database, I will end up executing two queries. One for the computer and another for the hardware.

Wouldn't it make sense to have 'loadComputerWithHardware' in my repository to save # of queries? Does it violate a rule of DDD (by querying a computer and hardware together by joining two tables)?

Was it helpful?

Solution

No one is forcing you to use lazy loading, it is common to do so when you have complex entity graphs but you can use eager loading if it suits you better. Note that even if you use lazy loading, this can be made transparent to the domain model.

One of the things that confuses me is that I should not access a child entity directly without accessing its aggregate root.

Well the idea is that the aggregate is the sole responsible for all the entities in its graph and so, all the operations performed in its graph should go through him, even the querying of individual nodes (child entities).

Wouldn't it make sense to have 'loadComputerWithHardware' in my repository to save # of queries?

Well, that's up to you but if you are not careful you might end up cluttering your interfaces. I'd stick with loadComputer and let each implementation of your data repository decide whenever it is better to do eager or lazy loading.

Does it violate a rule of DDD (by querying a computer and hardware together by joining two tables)?

No, "joining two tables" is not a domain concept, it is a data layer concern and they should be decoupled.

OTHER TIPS

The controller wouldn't know anything about the hardware. It only knows about the computer. It's the repository's responsibility to load everything the computer needs. If you need a reference to the hardware from the controller's point of view, it probably qualifies as an aggregate itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top