DDD – Repository for a Nested Entity

aggregatedomain-driven-designrepository

I have a AR called User, which has among other entities one called City.

The way I assign a City to a User is:
$user->addCity($city);

The problem comes when a id is given at some Controller endpoint instead of a City entity, I can't relate them if it's not through an instance and I can't retrieve the entity intance without a repository.

I could retrieve the entity with a CityRepository and then add it to the User but I though I should only use a repository for ARs.

For the moment, I'm getting the reference through Symfony's EntityManager:

    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }


    public function execute(Passenger $user, int $cityId, string $companyName = '')
    {
        $city = $this->users->getCityReferenceById($cityId);
        $user->addCity($city);
        ....
    }

while on UserRepository:

public function getCityReferenceById(int $cityId): City
{
    return $this->em->getReference(City::class, $cityId);
}

Best Answer

I think the question here is; do you need a whole city object for the User?

Fair a user is a resident in a city, but in this particular domain, are you concerned with the city details (name, country, etc) from the perspective of the user? or will just having the cityId suffice? - that is to say, would your require functionality to change the name, country, etc. of a city through a User?

If the Answer to the former is yes, then I suggest revisiting your Aggregate, perhaps User is not the AR here. If no, and you just want to have the full city details for the purpose of populating a view, then perhaps look into CQRS, which aims to separate concerns of query/read/display side by introducing a separate read model.