This article is reprinted from how to decouple: codedecoupled.com/php-es-reactor.html

A Reactor is almost the same as a Projector, the only difference being that we cannot replay the Reactor’s behavior. So the Reactor is designed to deal with side-effects behavior in the domain.

So what are side effects? An action can be interpreted as having a side effect if it occurs once rather than many times. For example, sending an email to the user when the order Completion event (OrderConfirmed) has a side effect because the user will receive a duplicate email when the order Completion event (OrderConfirmed) is replayed.

The following Reactor use cases are derived from our experience.

Practical use cases

Side effect behavior

Dealing with side effects in the domain is Reactor’s most intuitive use case. For example, sending an order email:

Interaggregation communication

We can use a Reactor when events communicate between two aggregates to complete a simple process. Suppose we set up two aggregations, Order and Bill. When the Order is confirmed, Bill automatically generates an Invoice, and we use the Reactor to communicate between the two aggregates:

There is a reason to emphasize the simplicity of this process. If a process is complex and long, we should use the Saga scenario because it supports rollback operations.

Events in translation field

When event traceability is used in conjunction with other architectural patterns, we need to deal with cross-architectural communication, which is where Reactor is used. For example, in the CRUD architecture, we also need to listen for domain events in event traceability. If we listen directly in CRUD, abstraction leakage will occur (domain events are abstract concepts in event traceability). At this point we can use Reactor to translate domain events into CRUD events and send them:

conclusion

A Reactor is like a special Projector. Like the Projector, it has a single, focused responsibility and is easy to write unit tests.

This article is reprinted from “Why Decouple” : codedecoupled.com/php-es-reactor.html. If you are also interested in TDD, DDD and clean code, please visit “Why Decouple” to explore the ways of software development.