Mariyo
Mariyo

Reputation: 506

DDD - domain service to store entity in not primary infrastructure

I am thinking about scenario in a way of Domain Driven design, where I have entity, lets say Cv (Curriculum vitae), which state is saved in database via repository.

Now I need to store part of the Cv in another system (ElasticSearch), which is crucial for whole app functionality like searching.

How to handle it? I am thinking about these 2 options:

1. Use domain service IndexCvGatewayServiceInterface (as interfaces implemented in infrastructure)

class CvEntity
{
    public function approve(CvRepositoryInterface $cvRepository, IndexCvGatewayServiceInterface $indexService)
    {
        $cvRepository->update($this);
        $indexService->update($this);
    }
}

2. Listen to domain event (create infrastructure listener)

class CvEntity
{
    public function approve(CvRepositoryInterface $cvRepository, EventDispatcheInterface $dispatcher)
    {
        $cvRepository->update($this);
        $dispatcher->dispatch(new CvApprovedEvent($this));
    }
}

I like option 2. because it separates logic for non state change purposes into infrastructure, but there is also concern, that we should know about searching as important part of our app.

Upvotes: 0

Views: 191

Answers (1)

Jorge
Jorge

Reputation: 207

You're facing here Write and Read model. Ideally after persist your entity/aggregate in the write model you should dispatch the uncommitted events of this entity and listing/subscribe to them to generate the projections (partials in elastic in your use case). For reference: https://github.com/jorge07/symfony-5-es-cqrs-boilerplate/blob/symfony-5/src/Infrastructure/User/ReadModel/Projections/UserProjectionFactory.php#L17 IMO, Entity should not contain the repository.

Upvotes: 0

Related Questions