A
A
AlpineMilk2021-08-11 14:30:05
PHP
AlpineMilk, 2021-08-11 14:30:05

How to interact with different contexts through events?

Hello everyone, I'm studying ddd and I have a question about events. Let's say there are 2 contexts: user, panel. We create a user and an event is created, UserWasCreatedEventwe throw this event somewhere in the queue. Next, in another panel context, we listen to an event UserWasCreatedEventfrom the user context and do something. And it turns out that the panel context has a direct dependence on the user context. Is this how it should be? How it is possible to get rid of this dependence to other context?
Sample code:

namespace User\Domain\Event;

class UserWasCreatedEvent
{
    // event data
}

---------------------------------------------

namespace Panel\Domain\Event;

use User\Domain\Event;

class UserWasCreatedEventHandler
{
    public function __invoke(UserWasCreatedEvent $createdEvent)
    {
        // do something
    }
}

---------------------------------------------

namespace Shared\Infrastructure\EventSubscriber\Doctrine;

class DomainEventSubscriber
{
    ...

    public function publish(): void
    {
        foreach ($this->entities as $entity) {
            foreach ($entity->releaseEvents() as $event) {
                $this->eventBus->dispatch($event);
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Ivchenkov, 2021-08-15
@Groonya

Next, in another panel context, we listen to the UserWasCreatedEvent event from the user context and do something.

You need to listen not in the panel context, but, for example, in the EventSubscriber context:
namespace Shared\Infrastructure\EventSubscriber\Doctrine;

use User\Domain\Event\UserWasCreatedEvent;
use Panel\Domain\SomeHandler;
use Panel\Domain\SomeCommand;

class UserWasCreatedEventHandler
{
    private SomeHandler $handler;

    public function __construct(SomeHandler $handler)
    {
        $this->handler = $handler;
    }

    public function __invoke(UserWasCreatedEvent $createdEvent)
    {
        $this->handler->handle(new SomeCommand(
            $createdEvent->getId(),
            $createdEvent->getSomeInfo()
        ));
    }
}

Thus, two independent contexts are connected at this point. The "mediator" pattern, if I'm not mistaken.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question