diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 53eba9f6..c3d816f1 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -85,7 +85,7 @@ export default defineConfig({ socialLinks: [ { icon: 'github', - link: 'https://github.com/cloudcreativity/ddd-modules', + link: 'https://github.com/cloudcreativity/php-ddd-modules', }, ], diff --git a/docs/guide/application/asynchronous-processing.md b/docs/guide/application/asynchronous-processing.md index a62bcbbe..08eb6cd0 100644 --- a/docs/guide/application/asynchronous-processing.md +++ b/docs/guide/application/asynchronous-processing.md @@ -17,7 +17,7 @@ allow command messages to be queued for asynchronous dispatch. There are two scenarios where a bounded context's work could be queued: - **Commands dispatched by the presentation and delivery layer** - but where the presentation layer does not need to - wait for the result of the command, i.e. prefers to return early. We refer to this as **external queueing**, as the + wait for the result of the command, i.e. prefers to return early. We refer to this as **external queuing**, as the request to queue the command comes from _outside_ your bounded context. - **Work executed as an internal implementation of your application layer.** A typical example is where a domain event listener queues work that needs to happen as a consequence of the domain event, but the execution of the work does not @@ -117,7 +117,7 @@ We could push this internal work to a queue via a domain event listener: ```php namespace App\Modules\EventManagement\Application\Orchestration\Listeners; -use App\Modules\EventManagement\Application\Ports\InternalQueue; +use App\Modules\EventManagement\Application\Ports\Queue\InternalQueue; use App\Modules\EventManagement\Application\Internal\RecalculateSalesAtEventCommand; use App\Modules\EventManagement\Domain\Events\AttendeeTicketWasCancelled; @@ -129,7 +129,7 @@ final readonly class QueueTicketSalesReportRecalculation public function handle(AttendeeTicketWasCancelled $event): void { - $this->queue->queue(new RecalculateSalesAtEventCommand( + $this->queue->push(new RecalculateSalesAtEventCommand( $event->eventId, )); } @@ -175,7 +175,7 @@ Define the internal command bus as follows: ```php namespace App\Modules\EventManagement\Application\Internal; -use CloudCreativity\Modules\Application\Ports\Driving\CommandBus\CommandDispatcher; +use CloudCreativity\Modules\Contracts\Messaging\CommandDispatcher; interface InternalCommandBus extends CommandDispatcher { diff --git a/docs/guide/application/commands.md b/docs/guide/application/commands.md index 4e80db04..a297c5d0 100644 --- a/docs/guide/application/commands.md +++ b/docs/guide/application/commands.md @@ -57,10 +57,11 @@ For example: ```php namespace App\Modules\EventManagement\Application\UseCases; +use App\Modules\EventManagement\Api\Input\CancelAttendeeTicketCommand; use App\Modules\EventManagement\Application\Ports\Persistence\AttendeeRepository; use CloudCreativity\Modules\Application\Bus\Middleware\ExecuteInUnitOfWork; use CloudCreativity\Modules\Toolkit\Pipeline\Through; -use CloudCreativity\Modules\Toolkit\Results\Result; +use CloudCreativity\Modules\Toolkit\Result\Result; #[Through(ExecuteInUnitOfWork::class)] final readonly class CancelAttendeeTicketHandler @@ -70,7 +71,7 @@ final readonly class CancelAttendeeTicketHandler ) { } - public function handle(CancelAttendeeTicketCommand $command): Result + public function execute(CancelAttendeeTicketCommand $command): Result { $attendee = $this->attendees->findOrFail($command->attendeeId); @@ -149,7 +150,7 @@ use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(LogMessageDispatch::class)] #[WithCommand(CancelAttendeeTicketCommand::class, CancelAttendeeTicketHandler::class)] -final class CommandBus extends CommandDispatcher implements Port +final class CommandBusAdapter extends CommandDispatcher implements Port { } ``` @@ -165,7 +166,7 @@ container. This container is then used to resolve any middleware and command han dispatcher via the `Through` and `WithCommand` attributes. ```php -$dispatcher = new CommandBus($psrContainer); +$dispatcher = new CommandBusAdapter($psrContainer); ``` So, for example in a Laravel application, you would bind this to the interface as follows in your service provider: @@ -184,7 +185,7 @@ $this->app->bind( ### Dispatching Commands You can now dispatch command messages to your bounded context from the _outside world_. For example, if we were using -a single action controller to handle a HTTP request in a Laravel application, we might dispatch a command like this: +a single action controller to handle an HTTP request in a Laravel application, we might dispatch a command like this: ```php namespace App\Http\Controllers\Api\Attendees; @@ -273,7 +274,7 @@ And then our implementation is as follows: ```php namespace App\Modules\EventManagement\Application\Adapters; -use App\Modules\EventManagement\Application\Ports\Queue; +use App\Modules\EventManagement\Application\Ports\Queue\Queue; use App\Modules\EventManagement\Api\CommandQueuer as Port; use CloudCreativity\Modules\Application\Bus\CommandQueuer as Queuer; @@ -368,7 +369,7 @@ Our `SetupBeforeDispatch` middleware allows setup work to be run before the comm teardown work when the command has completed. This allows you to set up any state and guarantee that the state is cleaned up, regardless of the outcome of the -command. The primary use case for this is to boostrap [Domain Services](../domain/services) and to garbage collect any +command. The primary use case for this is to bootstrap [Domain Services](../domain/services) and to garbage collect any singleton instances of dependencies. For example, bind an instance of the middleware into your service container: @@ -397,15 +398,15 @@ Here our setup middleware takes a setup closure as its only constructor argument return a closure to do any teardown work. The teardown callback is guaranteed to always be executed, regardless of whether a command succeeded or failed - and it also runs if an exception is thrown. -If you only need to do teardown work, use the `TeardownAfterDispatch` middleware instead. This takes a single teardown +If you only need to do teardown work, use the `TearDownAfterDispatch` middleware instead. This takes a single teardown closure as its only constructor argument: ```php -use CloudCreativity\Modules\Bus\Middleware\TeardownAfterDispatch; +use CloudCreativity\Modules\Bus\Middleware\TearDownAfterDispatch; $container->bind( - 'event:management:teardown', - fn () => new TeardownAfterDispatch(function (): Closure { + 'event-management:teardown', + fn () => new TearDownAfterDispatch(function (): void { // clean up work goes here. }), ); @@ -578,27 +579,26 @@ namespace App\Modules\EventManagement\Application\Adapters\Middleware; use Closure; use CloudCreativity\Modules\Contracts\Bus\Middleware\BusMiddleware; -use CloudCreativity\Modules\Contracts\Messaging\Command; -use CloudCreativity\Modules\Contracts\Messaging\Query; +use CloudCreativity\Modules\Contracts\Messaging\Message; use CloudCreativity\Modules\Contracts\Toolkit\Result\Result; class MyBusMiddleware implements BusMiddleware { /** - * Handle the command or query. + * Handle the message. * - * @param Command|Query $message - * @param Closure(Command|Query): Result $next - * @return Result + * @param Message $message + * @param Closure(Message): ?Result $next + * @return Result|null */ public function __invoke( - Command|Query $message, + Message $message, Closure $next, - ): Result + ): ?Result { // code here executes before the handler - $result = $next($command); + $result = $next($message); // code here executes after the handler diff --git a/docs/guide/application/domain-events.md b/docs/guide/application/domain-events.md index 126e724c..8a076c7c 100644 --- a/docs/guide/application/domain-events.md +++ b/docs/guide/application/domain-events.md @@ -52,8 +52,9 @@ To use this dispatcher, create a concrete implementation of your domain layer's namespace App\Modules\EventManagement\Application\Orchestration; use App\Modules\EventManagement\Domain\Events\DomainEventDispatcher as IDomainEventDispatcher; -use CloudCreativity\Modules\Application\DomainEventDispatching\UnitOfWorkAwareDispatcher; use CloudCreativity\Modules\Application\DomainEventDispatching\ListenTo; +use CloudCreativity\Modules\Application\DomainEventDispatching\Middleware\LogDomainEventDispatch; +use CloudCreativity\Modules\Application\DomainEventDispatching\UnitOfWorkAwareDispatcher; use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(LogDomainEventDispatch::class)] @@ -148,8 +149,7 @@ listeners and middleware. For example: ```php - -$dispatcher = new DomainEventDispatcher($container); +$dispatcher = new DomainEventDispatcherAdapter($container); ``` The main thing you need to ensure is that your instance of this domain event dispatcher is a singleton. This ensures @@ -190,7 +190,7 @@ final readonly class AttendeeTicketCancelled implements ``` :::warning -Doing this risks means side effects of the domain event will occur, even if something about the command handling +Doing this means side effects of the domain event will occur, even if something about the command handling subsequently fails. For example, if there is an error in your infrastructure layer when persisting state changes. This can compromise the consistency of your domain state. ::: @@ -270,7 +270,6 @@ namespace App\Modules\EventManagement\Application\Orchestration\Middleware; use Closure; use CloudCreativity\Modules\Contracts\Application\DomainEventDispatching\DomainEventMiddleware; use CloudCreativity\Modules\Contracts\Domain\Events\DomainEvent; -use CloudCreativity\Modules\Contracts\Toolkit\Result\Result; final class MyMiddleware implements DomainEventMiddleware { @@ -284,11 +283,11 @@ final class MyMiddleware implements DomainEventMiddleware public function __invoke( DomainEvent $event, Closure $next, - ): Result + ): void { // code here executes before the event is emitted. - $next($command); + $next($event); // code here executes after it is emitted. } diff --git a/docs/guide/application/integration-events.md b/docs/guide/application/integration-events.md index c8c7290c..966b362a 100644 --- a/docs/guide/application/integration-events.md +++ b/docs/guide/application/integration-events.md @@ -12,14 +12,14 @@ and any consuming bounded contexts. Integration events are bidirectional. They are both _published_ by a bounded context, and _consumed_ by other bounded contexts. This means we can refer to them in terms of their direction - specifically: -- **Inbound** integration events, are those a bounded context _consumes_ via an inbound event bus driving port. -- **Outbound** integration events, are those _published_ by a bounded context. Publishing occurs via a driven port, with +- **Inbound** integration events are those a bounded context _consumes_ via an inbound event bus driving port. +- **Outbound** integration events are those _published_ by a bounded context. Publishing occurs via a driven port, with the infrastructure layer implementing the adapter. ## Integration Event Messages Integration event messages are defined by writing a class that implements the `IntegrationEvent` interface. The class -should be named according to event it represents, and should contain properties that represent the data being exchanged. +should be named according to the event it represents, and should contain properties that represent the data being exchanged. The integration event interface is light-weight and defines only two methods: @@ -33,12 +33,12 @@ The integration event interface is light-weight and defines only two methods: For example: ```php -namespace App\Modules\EventManagement\Output\V1\Events; +namespace App\Modules\EventManagement\Api\Output\V1\Events; -use App\Modules\EventManagement\Output\V1\Enums\CancellationReasonEnum; +use App\Modules\EventManagement\Api\Output\V1\Enums\CancellationReasonEnum; use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; -use CloudCreativity\Modules\Toolkit\Identifiers\Uuid; +use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Uuid; final readonly class AttendeeTicketWasCancelled implements IntegrationEvent @@ -92,7 +92,7 @@ deserialization, the result will always be an identical integration event messag This can be expressed via an interface. To illustrate the point, a JSON serializer might look like this: ```php -namespace App\Modules\Ordering\Output\V1\Events\Serializers; +namespace App\Modules\Ordering\Api\Output\V1\Events\Serializers; use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; @@ -105,7 +105,7 @@ interface JsonSerializer public function serialize(IntegrationEvent $event): array; /** - * @param array + * @param array $input * @return IntegrationEvent */ public function deserialize(array $input): IntegrationEvent; @@ -169,7 +169,7 @@ For example: ```php namespace App\Modules\EventManagement\Application\Orchestration\Listeners; -use App\Modules\EventManagement\Application\Ports\OutboundEvents\OutboundEventBus; +use App\Modules\EventManagement\Application\Ports\OutboundEventBus\OutboundEventBus; use App\Modules\EventManagement\Domain\Events\AttendeeTicketWasCancelled; use App\Modules\EventManagement\Api\Output\V1\Events as IntegrationEvents; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\UuidFactory; @@ -187,7 +187,7 @@ final readonly class PublishAttendeeTicketWasCancelled $this->eventBus->publish( new IntegrationEvents\AttendeeTicketWasCancelled( uuid: $this->uuidFactory->uuid4(), - occurredAt: $event->occurredAt, + occurredAt: $event->getOccurredAt(), eventId: $event->eventId, attendeeId: $event->attendeeId, ticketId: $event->ticketId, @@ -212,7 +212,7 @@ In this scenario, the above listener would be changed to use the outbox instead: ```php namespace App\Modules\EventManagement\Application\Orchestration\Listeners; -use App\Modules\EventManagement\Application\Ports\OutboundEvents\Outbox; +use App\Modules\EventManagement\Application\Ports\OutboundEventBus\Outbox; use App\Modules\EventManagement\Domain\Events\AttendeeTicketWasCancelled; use App\Modules\EventManagement\Api\Output\V1\Events as IntegrationEvents; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\UuidFactory; @@ -230,7 +230,7 @@ final readonly class PublishAttendeeTicketWasCancelled $this->outbox->push( new IntegrationEvents\AttendeeTicketWasCancelled( uuid: $this->uuidFactory->uuid4(), - occurredAt: $event->occurredAt, + occurredAt: $event->getOccurredAt(), eventId: $event->eventId, attendeeId: $event->attendeeId, ticketId: $event->ticketId, @@ -279,7 +279,7 @@ An inbound event handler that dispatches a command that is a use case in your ap ```php namespace App\Modules\EventManagement\Application\UseCases\Events; -use App\Modules\EventManagement\Api\CommandBus\CommandBus; +use App\Modules\EventManagement\Api\CommandBus; use App\Modules\EventManagement\Api\Input\RecalculateSalesAtEventCommand; use App\Modules\Ordering\Api\Output\V1\Events\OrderWasFulfilled; @@ -292,7 +292,7 @@ final readonly class OrderWasFulfilledHandler public function handle(OrderWasFulfilled $event): void { - // alternatively we could use `queue()` to process the command asynchronously + // alternatively we could inject the `CommandQueuer` and use `queue()` to process the command asynchronously $this->bus->dispatch(new RecalculateSalesAtEventCommand( eventId: $event->eventId, )); @@ -310,7 +310,7 @@ command handler to do this. This is almost identical to the previous example. However, in this case the command is internal to the bounded context. I.e. it is not intended to be exposed as a use case that the outside world can dispatch. -This means the command message and command bus are in the application layer's driven ports namespace. Otherwise, the +This means the command message and command bus are in the application layer's `Internal` namespace. Otherwise, the approach is identical to the previous strategy. ```php @@ -351,8 +351,9 @@ namespace App\Modules\EventManagement\Application\UseCases\Events; use App\Modules\EventManagement\Domain\Events\DomainEventDispatcher; use App\Modules\EventManagement\Domain\Events\SalesAtEventDidChange; -use App\Modules\Ordering\Output\V1\Events\OrderWasFulfilled; +use App\Modules\Ordering\Api\Output\V1\Events\OrderWasFulfilled; use CloudCreativity\Modules\Application\Bus\Middleware\ExecuteInUnitOfWork; +use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(ExecuteInUnitOfWork::class)] final readonly class OrderWasFulfilledHandler @@ -372,7 +373,7 @@ final readonly class OrderWasFulfilledHandler ``` :::warning -If you are using this strategy and your bounded context uses unit of works, you must dispatch the event in a unit of +If you are using this strategy and your bounded context uses units of work, you must dispatch the event in a unit of work. This ensures that all side effects are committed or rolled back together. The above example does this via middleware. ::: @@ -403,11 +404,12 @@ namespace App\Modules\EventManagement\Application\Adapters; use App\Modules\EventManagement\Api\InboundEventBus as Port; use App\Modules\EventManagement\Application\UseCases\Events\DefaultEventHandler; use App\Modules\EventManagement\Application\UseCases\Events\OrderWasFulfilledHandler; -use App\Modules\Ordering\Output\V1\Events\OrderWasFulfilled; +use App\Modules\Ordering\Api\Output\V1\Events\OrderWasFulfilled; use CloudCreativity\Modules\Bus\InboundEventDispatcher; use CloudCreativity\Modules\Bus\WithDefault; use CloudCreativity\Modules\Bus\WithEvent; use CloudCreativity\Modules\Bus\Middleware\LogMessageDispatch; +use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(LogMessageDispatch::class)] #[WithDefault(DefaultEventHandler::class)] @@ -429,7 +431,7 @@ PSR container. This container is then used to resolve any middleware and event h dispatcher via the `Through`, `WithDefault` and `WithEvent` attributes. ```php -$dispatcher = new InboundEventBus($psrContainer); +$dispatcher = new InboundEventBusAdapter($psrContainer); ``` So, for example in a Laravel application, you would bind this to the interface as follows in your service provider: @@ -514,12 +516,13 @@ namespace App\Modules\EventManagement\Application\Adapters; use App\Modules\EventManagement\Api\InboundEventBus as Port; use App\Modules\EventManagement\Application\UseCases\Events\OrderWasFulfilledHandler; -use App\Modules\Ordering\Output\V1\Events\OrderWasFulfilled; +use App\Modules\Ordering\Api\Output\V1\Events\OrderWasFulfilled; use CloudCreativity\Modules\Bus\InboundEventDispatcher; use CloudCreativity\Modules\Bus\WithDefault; use CloudCreativity\Modules\Bus\WithEvent; use CloudCreativity\Modules\Bus\Middleware\LogMessageDispatch; use CloudCreativity\Modules\Bus\SwallowInboundEvent; +use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(LogMessageDispatch::class)] #[WithDefault(SwallowInboundEvent::class)] @@ -574,7 +577,7 @@ inbox. For both these actions - checking whether it exists, and storing - the ad might look like this: ```php -namespace App\Modules\EventManagement\Api\Ports\Inbox; +namespace App\Modules\EventManagement\Application\Ports\Inbox; use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; @@ -603,7 +606,7 @@ class InboundEventController extends Controller { public function __invoke( Request $request, - Inbox $inbox, + InboundEventInbox $inbox, JsonSerializer $serializer, ) { $validated = $request->validate([ @@ -658,11 +661,11 @@ middleware to suit your specific needs. ### Setup and Teardown -Our `SetupBeforeEvent` middleware allows your to run setup work before the event is published or notified, and +Our `SetupBeforeEvent` middleware allows you to run setup work before the event is dispatched, and optionally teardown work after. This allows you to set up any state, services or singletons - and guarantee that these are cleaned up, regardless of -whether the notifying or publishing completes or throws an exception. +whether handling the event completes or throws an exception. For example: @@ -685,7 +688,7 @@ Here our setup middleware takes a setup closure as its only constructor argument return a closure to do any teardown work. The teardown callback is guaranteed to always be executed - i.e. it will run even if an exception is thrown. -If you only need to do any teardown work, use the `TeardownAfterEvent` middleware instead. This takes a single teardown +If you only need to do teardown work, use the `TearDownAfterEvent` middleware instead. This takes a single teardown closure as its only constructor argument: ```php @@ -693,7 +696,7 @@ use CloudCreativity\Modules\Bus\Middleware\TearDownAfterEvent; $container->bind( 'event-management:teardown-events', - fn () => new TearDownAfterEvent(function (): Closure { + fn () => new TearDownAfterEvent(function (): void { // teardown here }), ); @@ -777,7 +780,7 @@ final class MyMiddleware implements IntegrationEventMiddleware { // code here executes before the event handler - $next($command); + $next($event); // code here executes after the event handler } @@ -786,6 +789,6 @@ final class MyMiddleware implements IntegrationEventMiddleware :::tip If you're writing middleware that is only meant to be used for a specific integration event, do not use the -`InboundEventMiddleware` interface. Instead, use the same signature but change the event type-hint to the event class +`IntegrationEventMiddleware` interface. Instead, use the same signature but change the event type-hint to the event class your middleware is designed to be used with. ::: diff --git a/docs/guide/application/queries.md b/docs/guide/application/queries.md index 6249cdd7..c5ac0d0e 100644 --- a/docs/guide/application/queries.md +++ b/docs/guide/application/queries.md @@ -16,7 +16,7 @@ I.e. it defines the data contract for the request. For example: ```php -namespace App\Modules\EventManagement\Api\Input\GetAttendeeTickets; +namespace App\Modules\EventManagement\Api\Input; use CloudCreativity\Modules\Contracts\Messaging\Query; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; @@ -41,10 +41,11 @@ Your query handler defines the use case - by type-hinting the query input and th ```php namespace App\Modules\EventManagement\Application\UseCases; +use App\Modules\EventManagement\Api\Input\GetAttendeeTicketsQuery; use App\Modules\EventManagement\Api\Output\V1\Models\TicketModel; use App\Modules\EventManagement\Application\Ports\Persistence\ReadModels\V1\TicketModelRepository; use App\Modules\EventManagement\Application\Factories\ReadModels\V1\TicketModelFactory; -use CloudCreativity\Modules\Toolkit\Results\Result; +use CloudCreativity\Modules\Toolkit\Result\Result; final readonly class GetAttendeeTicketsHandler { @@ -60,7 +61,7 @@ final readonly class GetAttendeeTicketsHandler * @param GetAttendeeTicketsQuery $query * @return Result> */ - public function handle(GetAttendeeTicketsQuery $query): Result + public function execute(GetAttendeeTicketsQuery $query): Result { $state = $this->repository->findByAttendeeId($query->attendeeId); @@ -95,7 +96,7 @@ handler executing business logic and returning a result representing the outcome ### Results -Just like commands, queries handlers return a result object - which contains the resulting data as its value. +Just like commands, query handlers return a result object - which contains the resulting data as its value. See the [Results chapter for information on using this object.](../toolkit/results) Unlike command results, query results can contain complex data structures as their return value. It is best to define @@ -130,10 +131,11 @@ use App\Modules\EventManagement\Application\UseCases\GetAttendeeTicketsHandler; use CloudCreativity\Modules\Bus\QueryDispatcher; use CloudCreativity\Modules\Bus\Middleware\LogMessageDispatch; use CloudCreativity\Modules\Bus\WithQuery; +use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(LogMessageDispatch::class)] #[WithQuery(GetAttendeeTicketsQuery::class, GetAttendeeTicketsHandler::class)] -final class QueryBus extends QueryDispatcher implements Port +final class QueryBusAdapter extends QueryDispatcher implements Port { } ``` @@ -149,7 +151,7 @@ container. This container is then used to resolve any middleware and query handl dispatcher via the `Through` and `WithQuery` attributes. ```php -$dispatcher = new QueryBus($psrContainer); +$dispatcher = new QueryBusAdapter($psrContainer); ``` So, for example in a Laravel application, you would bind this to the interface as follows in your service provider: @@ -168,7 +170,7 @@ $this->app->bind( ### Dispatching Queries You can now dispatch query messages to your bounded context from the _outside world_. For example, if we were using -a single action controller to handle a HTTP request in a Laravel application, we might dispatch a query like this: +a single action controller to handle an HTTP request in a Laravel application, we might dispatch a query like this: ```php namespace App\Http\Controllers\Api\Attendees; @@ -216,7 +218,7 @@ represents some current state of the bounded context. They are _read-only_ i.e. For example, our model returned by our "get attendee tickets" query might look like this: ```php -namespace App\Modules\EventManagement\Output\V1\Models; +namespace App\Modules\EventManagement\Api\Output\V1\Models; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; @@ -258,7 +260,7 @@ we wanted to display a list of all tickets. The ticket model can therefore exist attendee via an attendee identifier property. :::info -This is one of the big advantages of using the Command Query Responsibility Separation (CQRS) pattern. It allows you +This is one of the big advantages of using the Command Query Responsibility Segregation (CQRS) pattern. It allows you to structure the data required for write operations (commands) in a completely separate way to the data required to represent the current state of the system in response to read operations (queries). Each is modelled for their specific purpose. @@ -273,7 +275,7 @@ significantly. This is why it is important to start with a clear separation of c Read models may be consumed by other bounded contexts. For example, by a client that returns the read model it receives by calling your bounded context's microservice. -This mean you cannot make breaking changes to the data contract without updating every single consumer to use the new +This means you cannot make breaking changes to the data contract without updating every single consumer to use the new contract. In large systems, this can be a significant challenge. To mitigate this, you can version your read models. This @@ -293,7 +295,7 @@ version, and then remove the old version. ## Middleware Our query bus implementation gives you complete control over how to compose the handling of your queries, via -middleware. Middleware is a powerful way to add cross-cutting concerns to your command handling, such as logging. +middleware. Middleware is a powerful way to add cross-cutting concerns to your query handling, such as logging. Middleware can be added either to the query bus (so it runs for every query) or to individual query handlers. @@ -310,8 +312,8 @@ middleware to suit your specific needs. ### Setup and Teardown -If you need to do any setup and/or teardown work around dispatching a query, use our `SetupAndTeardown` or -`TeardownAfterDispatch` middleware. These are described [here in the Commands chapter.](./commands#setup-and-teardown) +If you need to do any setup and/or teardown work around dispatching a query, use our `SetupBeforeDispatch` or +`TearDownAfterDispatch` middleware. These are described [here in the Commands chapter.](./commands#setup-and-teardown) Their use is identical for queries. ### Logging @@ -355,7 +357,7 @@ final class MyMiddleware implements QueryMiddleware { // code here executes before the handler - $result = $next($command); + $result = $next($query); // code here executes after the handler @@ -378,27 +380,26 @@ namespace App\Modules\EventManagement\Application\Adapters\Middleware; use Closure; use CloudCreativity\Modules\Contracts\Bus\Middleware\BusMiddleware; -use CloudCreativity\Modules\Contracts\Messaging\Command; -use CloudCreativity\Modules\Contracts\Messaging\Query; +use CloudCreativity\Modules\Contracts\Messaging\Message; use CloudCreativity\Modules\Contracts\Toolkit\Result\Result; class MyBusMiddleware implements BusMiddleware { /** - * Handle the command or query. + * Handle the message. * - * @param Command|Query $message - * @param Closure(Command|Query): Result $next - * @return Result + * @param Message $message + * @param Closure(Message): ?Result $next + * @return Result|null */ public function __invoke( - Command|Query $message, + Message $message, Closure $next, - ): Result + ): ?Result { // code here executes before the handler - $result = $next($command); + $result = $next($message); // code here executes after the handler diff --git a/docs/guide/application/units-of-work.md b/docs/guide/application/units-of-work.md index 5bb54932..4d9c48ea 100644 --- a/docs/guide/application/units-of-work.md +++ b/docs/guide/application/units-of-work.md @@ -15,7 +15,7 @@ your domain model has no concept of how it is persisted. Consider the following scenario. Our domain models the attendees at an in-person event as having one-to-many tickets. When we want to cancel a ticket, we do this via the attendee aggregate root that contains the ticket entities. This is -because our domain logic says that state of the attendee may change when the ticket is cancelled. +because our domain logic says that the state of the attendee may change when the ticket is cancelled. Our command handler might look like this: @@ -24,7 +24,7 @@ namespace App\Modules\EventManagement\Application\UseCases; use App\Modules\EventManagement\Api\Input\CancelAttendeeTicketCommand; use App\Modules\EventManagement\Application\Ports\Persistence\AttendeeRepository; -use CloudCreativity\Modules\Toolkit\Results\Result; +use CloudCreativity\Modules\Toolkit\Result\Result; final readonly class CancelAttendeeTicketHandler { @@ -33,7 +33,7 @@ final readonly class CancelAttendeeTicketHandler ) { } - public function handle(CancelAttendeeTicketCommand $command): Result + public function execute(CancelAttendeeTicketCommand $command): Result { $attendee = $this->attendees->findOrFail($command->attendeeId); @@ -57,7 +57,7 @@ final readonly class CancelAttendeeTicketHandler This implementation poses a number of issues: -1. When the business action - _cancel ticket_ - is performed, the aggregate root and the relevant ticket entity is +1. When the business action - _cancel ticket_ - is performed, the aggregate root and the relevant ticket entity are updated to the new state (as defined by the business logic). 2. As its state is settled, the aggregate root emits a domain event so that other parts of the domain can react to the change. @@ -98,7 +98,7 @@ Given the above example, the correct order from the application perspective is: will be triggered later. 4. The aggregate root is persisted via the repository port. Internally within the adapter this may result in multiple database writes, that are within the transaction. -5. With the persistence changes successful made (but not yet committed), the deferred domain event is dispatched. +5. With the persistence changes successfully made (but not yet committed), the deferred domain event is dispatched. 6. Side effects of the domain event are triggered, within the transaction boundary. Any side effects that affect the persistence layer via driven ports now occur _after_ the aggregate changes were persisted. 7. The transaction is committed by closing the unit of work. The state changes to the aggregate root and the side @@ -112,11 +112,11 @@ All this is achieved by this package by combining the following: - **Unit of work manager** - an application concern that handles the lifecycle of the unit of work, e.g. deferring operations for later execution. - **Unit of work aware domain event dispatcher** - coordinates domain event dispatching with the unit of work manager. -- **Unit of work middleware** - that ensure command handlers and integration event consumers are executed in a unit of +- **Unit of work middleware** - ensures command handlers and integration event consumers are executed in a unit of work. :::info -The manager is high-level abstraction (provided by this package and part of the application layer) that manages the +The manager is a high-level abstraction (provided by this package and part of the application layer) that manages the lifecycle of the unit of work. The unit of work itself is a low-level abstraction (part of the infrastructure layer) that actually starts, commits and rolls back the transaction. ::: @@ -129,7 +129,7 @@ namespace App\Modules\EventManagement\Application\UseCases; use App\Modules\EventManagement\Api\Input\CancelAttendeeTicketCommand; use App\Modules\EventManagement\Application\Ports\Persistence\AttendeeRepository; use CloudCreativity\Modules\Application\Bus\Middleware\ExecuteInUnitOfWork; -use CloudCreativity\Modules\Toolkit\Results\Result; +use CloudCreativity\Modules\Toolkit\Result\Result; use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(ExecuteInUnitOfWork::class)] @@ -140,7 +140,7 @@ final readonly class CancelAttendeeTicketHandler ) { } - public function handle(CancelAttendeeTicketCommand $command): Result + public function execute(CancelAttendeeTicketCommand $command): Result { $attendee = $this->attendees->findOrFail($command->attendeeId); @@ -238,7 +238,7 @@ The unit of work manager is an application layer concern. It handles the complex When combined with the unit of work aware domain event dispatcher, it ensures domain event dispatching and side effects (via listeners) are coordinated within the unit of work. -The adapter just requires your concrete unit of work implementation: +The manager just requires your concrete unit of work implementation: ```php use CloudCreativity\Modules\Application\UnitOfWork\UnitOfWorkManager; @@ -246,7 +246,7 @@ use CloudCreativity\Modules\Contracts\Application\Ports\UnitOfWork; use CloudCreativity\Modules\Contracts\Application\Ports\ExceptionReporter; $manager = new UnitOfWorkManager( - db: $container->get(UnitOfWork::class), + unitOfWork: $container->get(UnitOfWork::class), reporter: $container->get(ExceptionReporter::class), ); ``` @@ -457,14 +457,14 @@ final readonly class QueueAttendeeCancellationEmail implements ``` :::warning -If any work pushed to after the unit of work has committed fails, it is not possible to rollback the transaction. This +If any work pushed to after the unit of work has committed fails, it is not possible to roll back the transaction. This means that the domain's new state will be committed, but your side effect has not occurred. This could lead to data inconsistencies. Use an [Outbox pattern](../infrastructure/outbox) to ensure data consistency. ::: -## Using Unit of Works +## Using Units of Work The unit of work pattern can be implemented on command handlers and integration event consumers. There is a consistent approach to all - use a middleware that wraps the execution in a unit of work. @@ -481,11 +481,12 @@ This means you should implement it on the handler itself, rather than adding it Use the `ExecuteInUnitOfWork` middleware to wrap command handlers in a unit of work: ```php -namespace App\Modules\EventManagement\Api\Input\CancelAttendeeTicket; +namespace App\Modules\EventManagement\Application\UseCases; +use App\Modules\EventManagement\Api\Input\CancelAttendeeTicketCommand; use App\Modules\EventManagement\Application\Ports\Persistence\AttendeeRepository; use CloudCreativity\Modules\Application\Bus\Middleware\ExecuteInUnitOfWork; -use CloudCreativity\Modules\Toolkit\Results\Result; +use CloudCreativity\Modules\Toolkit\Result\Result; use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(ExecuteInUnitOfWork::class)] @@ -496,7 +497,7 @@ final readonly class CancelAttendeeTicketHandler ) { } - public function handle(CancelAttendeeTicketCommand $command): Result + public function execute(CancelAttendeeTicketCommand $command): Result { $attendee = $this->attendees->findOrFail($command->attendeeId); @@ -534,7 +535,6 @@ use App\Modules\EventManagement\Domain\Events\DomainEventDispatcher; use App\Modules\EventManagement\Domain\Events\SalesAtEventDidChange; use App\Modules\Ordering\Api\Output\V1\Events\OrderWasFulfilled; use CloudCreativity\Modules\Application\Bus\Middleware\ExecuteInUnitOfWork; -use CloudCreativity\Modules\Contracts\Bus\DispatchThroughMiddleware; use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[Through(ExecuteInUnitOfWork::class)] diff --git a/docs/guide/concepts/bounded-contexts.md b/docs/guide/concepts/bounded-contexts.md index fad6b775..ce32af5c 100644 --- a/docs/guide/concepts/bounded-contexts.md +++ b/docs/guide/concepts/bounded-contexts.md @@ -18,7 +18,7 @@ of the warehouse, an order might be a set of items that need to be picked, packe customer, an order might be a set of items that they have purchased. In a monolith, these two concepts would be mixed together, leading to confusion and complexity. Your _Order_ entity -would end up being potentially thousands of lines long, with no clear clarity of whether it is being consumed in the +would end up being potentially thousands of lines long, with no clarity over whether it is being consumed in the context of the warehouse or the customer. By splitting your domain into bounded contexts, you can create a clear separation of concerns. Each bounded context @@ -40,7 +40,7 @@ package to implement a single module. However, it gives you the option of having a few bounded contexts - in which case you would have a few modules within that microservice. :::warning -If your microservice encompasses too many bounded contexts, you loose some of the benefits of a microservices +If your microservice encompasses too many bounded contexts, you lose some of the benefits of a microservices architecture. For example, it is important to keep your microservices small and focused, so they can be scaled independently. ::: diff --git a/docs/guide/concepts/encapsulation.md b/docs/guide/concepts/encapsulation.md index f76ffe97..91a5010e 100644 --- a/docs/guide/concepts/encapsulation.md +++ b/docs/guide/concepts/encapsulation.md @@ -58,13 +58,14 @@ layer defines how the bounded context reacts to these events. Integration events are bi-directional. They are both _published_ by the bounded context, and _consumed_ by the bounded context. This means we can refer to them in terms of their direction - specifically: -- **Outbound** integration events, are those _published_ by the bounded context. -- **Inbound** integration events, are those the bounded context _consumes_. - ::: +- **Outbound** integration events are those _published_ by the bounded context. +- **Inbound** integration events are those the bounded context _consumes_. + +::: ## Application Interface -The application layer of a bounded context defines its uses cases. These are the _commands_ and _queries_ that can be +The application layer of a bounded context defines its use cases. These are the _commands_ and _queries_ that can be dispatched to the bounded context, and the _integration events_ that the bounded context consumes. We follow a hexagonal architecture, where the application layer defines the _driving ports_ that it exposes to the @@ -86,7 +87,7 @@ interface Ticketing This is for illustrative purposes - you may not want to define an application interface like this as each driving port can be consumed separately. -However, it illustrates how the bounded context is fully encapsulated and described by the three messages types it can +However, it illustrates how the bounded context is fully encapsulated and described by the three message types it can handle. Everything else - e.g. domain entities containing business logic, coordination with the infrastructure layer, etc - is hidden as an internal implementation detail of your bounded context. @@ -148,7 +149,7 @@ bounded context: - A `GET` request would result in a query message being dispatched to the bounded context _within_ the microservice - with the resulting state being returned in the HTTP response. -- A `POST` request would result in a command message being dispatched to the bounded context _within_ in the +- A `POST` request would result in a command message being dispatched to the bounded context _within_ the microservice. It may also result in a query message if the API is returning the current state of the context in the HTTP response. ::: diff --git a/docs/guide/concepts/index.md b/docs/guide/concepts/index.md index 82e7732c..a15a23c1 100644 --- a/docs/guide/concepts/index.md +++ b/docs/guide/concepts/index.md @@ -1,6 +1,6 @@ # Core Concepts -This section of the guide provides the core conceptual concepts that underpin the design of this package. +This section of the guide provides the core concepts that underpin the design of this package. ## Bounded Contexts diff --git a/docs/guide/concepts/layers.md b/docs/guide/concepts/layers.md index 53d9cdca..bf2d37b0 100644 --- a/docs/guide/concepts/layers.md +++ b/docs/guide/concepts/layers.md @@ -14,7 +14,7 @@ The layers within this architecture are as follows - starting from the inner-mos The domain layer contains the domain entities, aggregate roots and business logic. It is the core of the module and should be entirely encapsulated - i.e. it must not depend on any other layer. This allows you to structure your domain -entities and aggregate roots in a way that cleanly encapsulate business logic, ensuring the logic is easy to reason +entities and aggregate roots in a way that cleanly encapsulates business logic, ensuring the logic is easy to reason about and test. :::tip @@ -41,7 +41,7 @@ interfaces. There are two types of ports: - **Driving Ports** (aka _primary_ or _input_ ports) - interfaces that define the use cases of the bounded context. These are implemented by application services, and are used by adapters in the outside world to initiate interactions - with the application. For example, an adapter could be a HTTP controller that takes input from a request and passes it + with the application. For example, an adapter could be an HTTP controller that takes input from a request and passes it to the application via a driving port. - **Driven Ports** (aka _secondary_ or _output_ ports) - interfaces that define the dependencies of the application layer. The adapters that implement these interfaces are in the infrastructure layer. For example, a persistence port @@ -70,7 +70,7 @@ This means that there are three types of _messages_ that define the use cases of This layer contains adapters that implement the driven ports defined in the application layer. -This is an _dependency inversion_ principle. The application defines what it needs from the infrastructure layer, and +This is the _dependency inversion_ principle. The application defines what it needs from the infrastructure layer, and the infrastructure layer provides the implementations. This means that the application layer never depends on the infrastructure layer. Anything it needs to interact with must be defined as a driven port. @@ -106,7 +106,7 @@ are provided by that layer. This means it can only: 2. Execute queries to read the state of the domain. 3. Notify the application layer of an integration event inbound from another module. -Which you may notice is the three message types described in the application layer above. :tada: +Which you may notice are the three message types described in the application layer above. :tada: ## Frameworks @@ -134,7 +134,7 @@ The _presentation and delivery_ components it provides include: 2. HTML generation via Blade templates. 3. JSON resource responses. 4. Console command handling and scheduling. -4. Etc. +5. Etc. :::info This package is framework agnostic, so you can use it with any framework - or even any legacy application that does not diff --git a/docs/guide/concepts/modularisation.md b/docs/guide/concepts/modularisation.md index 8ef171a8..263e350e 100644 --- a/docs/guide/concepts/modularisation.md +++ b/docs/guide/concepts/modularisation.md @@ -2,7 +2,7 @@ Modularisation is an approach to splitting up a monolith, particularly one that is considered _legacy_ code, into smaller, more manageable pieces. By adopting a domain-centric approach, this package provides the tooling needed to -modularise a monolith - and how these modules can be transitioned to a microservices architecture over time. +modularise a monolith - and shows how these modules can be transitioned to a microservices architecture over time. ## Why Modularise? @@ -27,7 +27,7 @@ immediately as a microservice while using this package to ensure they are implem modules. :::tip -This chapters shows how we choose to structure our modules. There is nothing about the package's implementation that +This chapter shows how we choose to structure our modules. There is nothing about the package's implementation that forces you to use this structure. However, we've described our preferred structure as we believe that it provides a good starting point for most projects. ::: @@ -67,8 +67,8 @@ As a top-level summary, the namespaces in each module are: cases of the module are implemented (e.g. via command and query handlers). 3. **Infrastructure** - the adapters that implement the application's driven ports. 4. **Api** - the public interface for interacting with the module, i.e. by the presentation and delivery layer. This - holds the _input_ contracts and value objects that can be used externally (including the driving ports) and the _ - output) values that are received as a result of interacting with the module. + holds the _input_ contracts and value objects that can be used externally (including the driving ports) and the + _output_ values that are received as a result of interacting with the module. :::tip Note that there is no _presentation layer_ here. Presentation and delivery is _outside_ the `Modules` namespace. This is @@ -126,7 +126,7 @@ For example: The `Api` namespace makes it extremely easy to enforce your architectural layers in the presentation and delivery layer. If you're using a tool like [Deptrac](https://github.com/deptrac/deptrac) you can specify that the presentation and delivery layer can only consume classes from the API namespace of the module. This ensures that there is no incorrect -use of the application, domain and infrastrucute layers - enforcing encapsulation. +use of the application, domain and infrastructure layers - enforcing encapsulation. ::: ### Application Namespace @@ -136,7 +136,7 @@ The application namespace can be structured as follows: ``` - Application - Ports <- driven ports - - OutboundEvents + - OutboundEventBus - Queue - Persistence - ... @@ -145,10 +145,10 @@ The application namespace can be structured as follows: - QueryBusAdapter - InboundEventBusAdapter - UseCases - - Internal <- internal use cases, e.g. for asynchronous processing - - ... - - FooCommandHandler <- uses cases + - FooCommandHandler <- use cases - BarQueryHandler + - Internal <- internal use cases, e.g. for asynchronous processing + - ... - Orchestration <- orchestration of domain and infrastructure layers ``` @@ -156,11 +156,12 @@ The namespaces shown here are as follows: - **Ports** - the driven ports of the application layer expressed as interfaces. The driven ports are the interfaces that the application layer expects to be implemented by the infrastructure layer. -- **Adapter** - contains the implementations of the driving ports. The concrete implementations are the command bus, +- **Adapters** - contains the implementations of the driving ports. The concrete implementations are the command bus, query bus, and inbound event bus. Each bus ensures a message is dispatched to the correct handler. - **Use Cases** - the implementation of the business logic of the application layer, i.e. how the application layer - handles inbound commands, queries and integration events. Additionally we use an `Internal` namespace in here for - organising the use cases that are for internal use by the module only - i.e. asynchronous processing. + handles inbound commands, queries and integration events. +- **Internal** - the use cases that are for internal use by the module only - i.e. asynchronous processing. This + includes the internal commands, their handlers and the internal command bus. - **Orchestration** - any classes required to help coordinate with the domain layer. For example, this is where the concrete implementation of the domain event dispatcher will go, along with domain event listeners. diff --git a/docs/guide/domain/entities.md b/docs/guide/domain/entities.md index eea54f69..d65a3659 100644 --- a/docs/guide/domain/entities.md +++ b/docs/guide/domain/entities.md @@ -121,6 +121,31 @@ There are two different schools of thought on how to implement entity identifier 2. Type-hint the expected identifier type, e.g. `Uuid` or even more specific like `UuidV7`. This is more explicit, and can be useful where you want to constrain the identifier type. +If you use the second approach, use the `IsEntityWithTypedId` trait. This implements the entity interface methods +without declaring the `$id` property, so that you can declare it with your expected type: + +```php +namespace App\Modules\EventManagement\Domain; + +use CloudCreativity\Modules\Contracts\Domain\Entity; +use CloudCreativity\Modules\Domain\IsEntityWithTypedId; +use CloudCreativity\Modules\Toolkit\Identifiers\UuidV7; + +final class BookableEvent implements Entity +{ + use IsEntityWithTypedId; + + public function __construct( + private readonly UuidV7 $id, + public readonly \DateTimeImmutable $startsAt, + public readonly \DateTimeImmutable $endsAt, + ) { + } + + // ...methods +} +``` + Both approaches work. However, we'd generally recommend that if using the second approach, you use globally unique identifiers rather than something like an auto-incrementing integer. This is because globally unique identifiers are more flexible, and can be used across different persistence implementations without coupling the domain layer to a @@ -148,6 +173,7 @@ namespace App\Modules\EventManagement\Domain; use CloudCreativity\Modules\Contracts\Domain\AggregateRoot; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; use CloudCreativity\Modules\Domain\IsEntity; +use CloudCreativity\Modules\Toolkit\Contracts; final class Attendee implements AggregateRoot { @@ -156,7 +182,7 @@ final class Attendee implements AggregateRoot public function __construct( Identifier $id, public readonly Customer $customer, - private(set) ListOfTickets $tickets, + private(set) readonly ListOfTickets $tickets, ) { Contracts::assert( $this->tickets->isNotEmpty(), @@ -171,7 +197,7 @@ final class Attendee implements AggregateRoot ``` :::tip -See the [Assertions Chapter](../toolkit/assertions) for an explanation of the `Contract::assert()` helper. +See the [Assertions Chapter](../toolkit/assertions) for an explanation of the `Contracts::assert()` helper. ::: ### Mutating State @@ -204,6 +230,7 @@ public function cancelTicket( $ticket->markAsCancelled($reason); Services::getEvents()->dispatch(new AttendeeTicketWasCancelled( + eventId: $this->eventId, attendeeId: $this->id, ticketId: $ticketId, reason: $reason, diff --git a/docs/guide/domain/events.md b/docs/guide/domain/events.md index 2e74996a..dc215ef4 100644 --- a/docs/guide/domain/events.md +++ b/docs/guide/domain/events.md @@ -58,7 +58,7 @@ final readonly class AttendeeTicketWasCancelled implements ) { } - public function getOccurredAt(): DateTimeImmutable + public function getOccurredAt(): \DateTimeImmutable { return $this->cancelledAt; } @@ -267,21 +267,21 @@ For this, we need a listener in the application layer that will queue a command example: ```php -namespace App\Modules\EventManagement\Application\Internal\DomainEvents\Listeners; +namespace App\Modules\EventManagement\Application\Orchestration\Listeners; -use App\Modules\EventManagement\Application\Ports\Driving\CommandBus\InternalCommandBus; -use App\Modules\EventManagement\Application\Internal\Commands\RecalculateSalesAtEvent\RecalculateSalesAtEventCommand; +use App\Modules\EventManagement\Application\Internal\RecalculateSalesAtEventCommand; +use App\Modules\EventManagement\Application\Ports\Queue\InternalQueue; use App\Modules\EventManagement\Domain\Events\AttendeeTicketWasCancelled; final readonly class QueueTicketSalesReportRecalculation { - public function __construct(private InternalCommandBus $bus) + public function __construct(private InternalQueue $queue) { } public function handle(AttendeeTicketWasCancelled $event): void { - $this->bus->queue(new RecalculateSalesAtEventCommand( + $this->queue->push(new RecalculateSalesAtEventCommand( $event->eventId, )); } @@ -290,7 +290,7 @@ final readonly class QueueTicketSalesReportRecalculation :::tip The pattern of queuing work internal to a bounded context is described in our -[Asynchronous Processing chapter](../application/asynchronous-processing) in the infrastructure layer. +[Asynchronous Processing chapter](../application/asynchronous-processing) in the application layer. ::: ### Publishing Integration Events @@ -311,12 +311,12 @@ of a domain event. Our listener to do this might look like this: ```php -namespace App\Modules\EventManagement\Application\Internal\DomainEvents\Listeners; +namespace App\Modules\EventManagement\Application\Orchestration\Listeners; use App\Modules\EventManagement\Application\Ports\OutboundEventBus\OutboundEventBus; use App\Modules\EventManagement\Domain\Events\AttendeeTicketWasCancelled; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\UuidFactory; -use VendorName\EventManagement\Shared\IntegrationEvents\V1 as IntegrationEvents; +use App\Modules\EventManagement\Api\Output\V1\Events as IntegrationEvents; final readonly class PublishAttendeeTicketWasCancelled { @@ -331,7 +331,7 @@ final readonly class PublishAttendeeTicketWasCancelled $this->publisher->publish( new IntegrationEvents\AttendeeTicketWasCancelled( uuid: $this->uuidFactory->uuid4(), - occurredAt: $event->occurredAt, + occurredAt: $event->getOccurredAt(), eventId: $event->eventId, attendeeId: $event->attendeeId, ticketId: $event->ticketId, diff --git a/docs/guide/domain/services.md b/docs/guide/domain/services.md index 98db82b7..eade3f38 100644 --- a/docs/guide/domain/services.md +++ b/docs/guide/domain/services.md @@ -107,20 +107,20 @@ final readonly class CanTransferFundsHandler * @param CanTransferFundsQuery $query * @return Result> */ - public function execute(TransferFundsCommand $command): Result + public function execute(CanTransferFundsQuery $query): Result { $sourceAccount = $this->bankAccountRepository->findOrFail( - $command->sourceId, + $query->sourceId, ); $destinationAccount = $this->bankAccountRepository->findOrFail( - $command->destinationId, + $query->destinationId, ); $reasons = $this->transferFundsService->canTransfer( source: $sourceAccount, destination: $destinationAccount, - amount: $command->amount, + amount: $query->amount, ); $models = []; @@ -164,6 +164,11 @@ injected via a setter. Ok, that's a bit wordy! This example illustrates what we mean: ```php +namespace App\Modules\BankAccounts\Domain; + +use App\Modules\BankAccounts\Domain\Services\TransferFundsService; +use Closure; + final class Services { /** diff --git a/docs/guide/domain/value-objects.md b/docs/guide/domain/value-objects.md index 73440bd5..64c6bd71 100644 --- a/docs/guide/domain/value-objects.md +++ b/docs/guide/domain/value-objects.md @@ -12,7 +12,7 @@ of your domain. However, this chapter provides some examples and guidance on bes ## Examples :::tip -PHP 8 `readonly public` properties are great for the value object use-case. They ensure immutability, while removing +PHP 8.1 `public readonly` properties are great for the value object use-case. They ensure immutability, while removing the need to write lots of boilerplate "getter" methods. ::: @@ -54,7 +54,7 @@ final readonly class Customer public function __construct( public string $firstName, public string $lastName, - public EmailAddress $this->value, + public EmailAddress $email, ) { } } @@ -122,7 +122,7 @@ class ListOfTickets implements ListIterator public function allCancelled(): bool { - foreach ($this->tickets as $ticket) { + foreach ($this->stack as $ticket) { if ($ticket->isNotCancelled()) { return false; } @@ -236,7 +236,7 @@ make your codebase predictable and easier to understand. ### DateTimes PHP provides a `DateTime` class, but it is not immutable. You should **never** use this, because it breaks the -immutability principal of value objects. +immutability principle of value objects. Instead, use PHP's `DateTimeImmutable` class, which does guarantee immutability. @@ -277,7 +277,7 @@ Value objects must always have object equality. This means that two value object same values, even if they are different instances. In PHP, a good tip is to put the equality logic in an `equals()` method. This gives you a fluent interface for checking -whether two values are equally. Additionally, you can then use PHPUnit's `assertObjectEquals()` assertion to ensure +whether two values are equal. Additionally, you can then use PHPUnit's `assertObjectEquals()` assertion to ensure two value objects are equal in tests - which is a nice benefit. For example, we can improve the example customer value object as follows: @@ -296,7 +296,7 @@ final readonly class Customer { return $this->firstName === $other->firstName && $this->lastName === $other->lastName && - $this->email->equals($other->email); + $this->email->value === $other->email->value; } } ``` @@ -388,4 +388,4 @@ Value objects should not be mocked in tests. This is because they enforce invari incorrectly constructed. Mocking them breaks this rule, as a mock could be configured with invalid values. Luckily, if you write your value objects like the examples in this chapter, you'll find that you cannot mock them -in unit tests. Declaring a class `final` and/or `readonly` both prevent a class from being mocked. +in unit tests. Declaring a class `final` prevents it from being mocked. diff --git a/docs/guide/infrastructure/exception-reporting.md b/docs/guide/infrastructure/exception-reporting.md index 4dd41312..fcb93a0d 100644 --- a/docs/guide/infrastructure/exception-reporting.md +++ b/docs/guide/infrastructure/exception-reporting.md @@ -22,7 +22,7 @@ try { $this->someService->doSomething(); return true; } catch (\Throwable $e) { - $this->logger->error('An error occurred: ', $e->getMessage()); + $this->logger->error('An error occurred: ' . $e->getMessage()); return false; } ``` @@ -80,7 +80,7 @@ layer to any logging service you are using. If all you need to do is log a reported exception as an error, we provide a default implementation that uses a PSR logger. The implementation is: `CloudCreativity\Modules\Infrastructure\ExceptionReporter\PsrLogExceptionReporter` -Provide an instance of the PSR Log as the only constructor argument. +Provide an instance of a PSR logger as the only constructor argument. ### Laravel Example @@ -111,7 +111,7 @@ final readonly class ExceptionReporterAdapter implements ## Testing We provide a fake exception reporter that you can use in tests. This is the -`CloudCreativity\Modules\Testing\FakeUnitOfWork` class. +`CloudCreativity\Modules\Testing\FakeExceptionReporter` class. You can access any exceptions that were reported via the `$reported` property: diff --git a/docs/guide/infrastructure/outbox.md b/docs/guide/infrastructure/outbox.md index 431a7dae..d26a7c35 100644 --- a/docs/guide/infrastructure/outbox.md +++ b/docs/guide/infrastructure/outbox.md @@ -34,7 +34,7 @@ So what happens if we move them outside the transaction boundary, i.e. ensuring effects are executed after the commit? Now the problem is that we cannot guarantee _all_ the side-effects will occur. We might successfully publish to the -event bus, but if we encounter a temporary Redis failure both the asynchronous recalculation and the emailing will not +event bus, but if we encounter a temporary Redis failure neither the asynchronous recalculation nor the emailing will occur. ## Solution @@ -60,7 +60,7 @@ bus. Our recommended approach is to first place these events into an outbox. This means we need a driven port for the outbox: ```php -namespace App\Modules\EventManagement\Application\Ports\OutboundEvents; +namespace App\Modules\EventManagement\Application\Ports\OutboundEventBus; use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; @@ -81,7 +81,7 @@ Domain event listeners would then use this instead of publishing the event thems ```php namespace App\Modules\EventManagement\Application\Orchestration\Listeners; -use App\Modules\EventManagement\Application\Ports\OutboundEvents\Outbox; +use App\Modules\EventManagement\Application\Ports\OutboundEventBus\Outbox; use App\Modules\EventManagement\Domain\Events\AttendeeTicketWasCancelled; use App\Modules\EventManagement\Api\Output\V1\Events as IntegrationEvents; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\UuidFactory; @@ -99,7 +99,7 @@ final readonly class PublishAttendeeTicketWasCancelled $this->outbox->push( new IntegrationEvents\AttendeeTicketWasCancelled( uuid: $this->uuidFactory->uuid4(), - occurredAt: $event->occurredAt, + occurredAt: $event->getOccurredAt(), eventId: $event->eventId, attendeeId: $event->attendeeId, ticketId: $event->ticketId, diff --git a/docs/guide/infrastructure/persistence.md b/docs/guide/infrastructure/persistence.md index 8647bd39..ceeef7e6 100644 --- a/docs/guide/infrastructure/persistence.md +++ b/docs/guide/infrastructure/persistence.md @@ -6,11 +6,11 @@ retrieved across different runs of the program, or even across different program This package does not provide any specific persistence concerns. This is because persistence is highly dependent on the specific use case and the infrastructure of the application. Instead, this chapter provides some guidance and best -practices on how to implement persistence in domain-driven way. +practices on how to implement persistence in a domain-driven way. ## Read vs Write Models -In the context of Domain Driven Design, persistence is the mechanisms by which: +In the context of Domain Driven Design, persistence refers to the mechanisms by which: - aggregate roots and entities are stored, updated and retrieved; and - current state is questioned (queried) and answered via [read models.](../application/queries#read-models) @@ -75,9 +75,8 @@ The first port would need to be used by our "cancel ticket" command to retrieve state back: ```php -namespace App\Modules\EventManagement\Application\Ports\Persistence\AttendeeRepository; +namespace App\Modules\EventManagement\Application\Ports\Persistence; -use App\Modules\EventManagement\Domain\Attendee; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; interface AttendeeRepository @@ -90,7 +89,7 @@ interface AttendeeRepository The second port would be used by our "get all tickets" query: ```php -namespace App\Modules\EventManagement\Application\Ports\Persistence\ReadModels\V1\TicketModelRepository; +namespace App\Modules\EventManagement\Application\Ports\Persistence\ReadModels\V1; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; @@ -120,9 +119,8 @@ To return to our example of an attendee aggregate root that contains ticket enti store and retrieve the ticket entities. This means we only need one port: ```php -namespace App\Modules\EventManagement\Application\Ports\Persistence\AttendeeRepository; +namespace App\Modules\EventManagement\Application\Ports\Persistence; -use App\Modules\EventManagement\Domain\Attendee; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; interface AttendeeRepository @@ -209,7 +207,7 @@ use App\Modules\EventManagement\Application\Ports\Persistence\AttendeeState; use App\Modules\EventManagement\Application\Ports\Persistence\AttendeeUpdateState; use App\Modules\EventManagement\Application\Ports\Persistence\TicketState; use App\Models\Attendee as AttendeeModel; -use App\Models\Attendee as TicketModel; +use App\Models\Ticket as TicketModel; use CloudCreativity\Modules\Contracts\Toolkit\Identifiers\Identifier; use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId; @@ -256,12 +254,12 @@ ticket read model. Whether this mapping is efficient enough for your use case, only you can decide. When first implementing your bounded context, you might find it easy to start with Eloquent. For example, loading an -attendee Eloquent model with ticket models eager loaded is straight forward. +attendee Eloquent model with ticket models eager loaded is straightforward. However, under the hood this is potentially inefficient. Eloquent is loading a row from a database, then hydrating an Eloquent model - for you to then immediately map that to an aggregate root. As your application scales, you might find that the performance of this approach is not sufficient. At that point, you -can choose to implement a repository that directly uses the database row. The good thing hexagonal architecture is that +can choose to implement a repository that directly uses the database row. The good thing about hexagonal architecture is that you can do this without changing your domain model, logic or application layer. ::: diff --git a/docs/guide/infrastructure/publishing-events.md b/docs/guide/infrastructure/publishing-events.md index 611bbeb8..0dcb8917 100644 --- a/docs/guide/infrastructure/publishing-events.md +++ b/docs/guide/infrastructure/publishing-events.md @@ -61,6 +61,7 @@ specific closures to specific events, and add middleware to the publisher. Here' ```php namespace App\Modules\EventManagement\Infrastructure\OutboundEventBus; +use App\Modules\EventManagement\Api\Output\V1\Events\AttendeeTicketWasCancelled; use App\Modules\EventManagement\Application\Ports\OutboundEventBus\OutboundEventBus; use App\Modules\EventManagement\Infrastructure\GooglePubSub\EventSerializer; use App\Modules\EventManagement\Infrastructure\GooglePubSub\SecureTopicFactory; @@ -68,7 +69,6 @@ use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\Middleware\LogOutboundEvent; use CloudCreativity\Modules\Toolkit\Pipeline\PipeContainer; use Psr\Log\LoggerInterface; -use VendorName\EventManagement\Shared\IntegrationEvents\V1\AttendeeTicketWasCancelled; final readonly class OutboundEventBusAdapterProvider { @@ -110,7 +110,7 @@ final readonly class OutboundEventBusAdapterProvider ); /** Attach middleware that runs for all events */ - $bus->through([ + $publisher->through([ LogOutboundEvent::class, ]); @@ -133,12 +133,12 @@ use App\Modules\EventManagement\Application\Ports\OutboundEventBus\OutboundEvent use CloudCreativity\Modules\Infrastructure\OutboundEventBus\ComponentPublisher; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\DefaultPublisher; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\Publishes; -use CloudCreativity\Modules\Toolkit\Pipeline\Through; +use App\Modules\EventManagement\Api\Output\V1\Events\AttendeeTicketWasCancelled; use CloudCreativity\Modules\Infrastructure\OutboundEventBus\Middleware\LogOutboundEvent; +use CloudCreativity\Modules\Toolkit\Pipeline\Through; #[DefaultPublisher(MyDefaultPublisher::class)] -#[Publishes(FooIntegrationEvent::class, FoobarPublisher::class)] -#[Publishes(BarIntegrationEvent::class, BazbatPublisher::class)] +#[Publishes(AttendeeTicketWasCancelled::class, AttendeeTicketWasCancelledPublisher::class)] #[Through(LogOutboundEvent::class)] final class OutboundEventBusAdapter extends ComponentPublisher implements OutboundEventBus @@ -158,7 +158,11 @@ follows: ```php namespace App\Modules\EventManagement\Infrastructure\OutboundEventBus; -final class DefaultPublisher +use App\Modules\EventManagement\Infrastructure\GooglePubSub\EventSerializer; +use App\Modules\EventManagement\Infrastructure\GooglePubSub\SecureTopicFactory; +use CloudCreativity\Modules\Contracts\Messaging\IntegrationEvent; + +final class MyDefaultPublisher { public function __construct( private SecureTopicFactory $topicFactory, @@ -181,6 +185,8 @@ And then we could also define a handler for a specific event: namespace App\Modules\EventManagement\Infrastructure\OutboundEventBus; use App\Modules\EventManagement\Api\Output\V1\Events\AttendeeTicketWasCancelled; +use App\Modules\EventManagement\Infrastructure\GooglePubSub\EventSerializer; +use App\Modules\EventManagement\Infrastructure\GooglePubSub\SecureTopicFactory; final class AttendeeTicketWasCancelledPublisher { @@ -236,7 +242,7 @@ how that works. ## Middleware -Our inbound event bus implementation gives you complete control over how to compose the handling of integration events, +Our outbound event bus implementations gives you complete control over how to compose the handling of integration events, via middleware. Middleware is a powerful way to add cross-cutting concerns to your event handling, such as logging. To apply middleware to the outbound event bus, use the `through()` method - as shown in the earlier examples. @@ -260,7 +266,7 @@ You can write your own middleware to suit your specific needs. Middleware is a s following signature: ```php -namespace App\Modules\EventManagement\Application\Adapters\Middleware; +namespace App\Modules\EventManagement\Infrastructure\OutboundEventBus\Middleware; use Closure; use CloudCreativity\Modules\Contracts\Bus\Middleware\IntegrationEventMiddleware; @@ -280,11 +286,11 @@ final class MyMiddleware implements IntegrationEventMiddleware Closure $next, ): void { - // code here executes before the event handler + // code here executes before the event is published - $next($command); + $next($event); - // code here executes after the event handler + // code here executes after the event is published } } ``` diff --git a/docs/guide/infrastructure/queues.md b/docs/guide/infrastructure/queues.md index d6a37449..768f66a9 100644 --- a/docs/guide/infrastructure/queues.md +++ b/docs/guide/infrastructure/queues.md @@ -88,6 +88,7 @@ use App\Modules\EventManagement\Application\Ports\Queue\Queue; use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Infrastructure\Queue\Middleware\LogPushedToQueue; use CloudCreativity\Modules\Toolkit\Pipeline\PipeContainer; +use Psr\Log\LoggerInterface; final class QueueAdapterProvider { @@ -110,7 +111,7 @@ final class QueueAdapterProvider fn () => new LogPushedToQueue($this->logger), ); - $queue->through([LogPushedToQueue::class]); + $adapter->through([LogPushedToQueue::class]); return $adapter; } @@ -141,7 +142,7 @@ $queue->bind( ## Class-Based Queuing -Our `ComponentQueue` allows you to use define queuing logic on classes. Each class is an _enqueuer_ - a component that +Our `ComponentQueue` allows you to define queuing logic on classes. Each class is an _enqueuer_ - a component that handles pushing an item (in this case a command message) onto a queue. This is useful in scenarios where you want to use constructor dependency injection when integrating with your PHP @@ -161,8 +162,8 @@ use CloudCreativity\Modules\Infrastructure\Queue\DefaultEnqueuer; use CloudCreativity\Modules\Infrastructure\Queue\Queues; #[DefaultEnqueuer(MyDefaultEnqueuer::class)] -#[Queues(SomeCommand::class, SomeCommandEnqueuer::class)] -#[Queues([SomeOtherCommand::class, YetAnotherCommand::class], SomeOtherCommandEnqueuer::class)] +#[Queues(RecalculateSalesAtEventCommand::class, ReportingEnqueuer::class)] +#[Queues([SomeCommand::class, SomeOtherCommand::class], SomeOtherEnqueuer::class)] #[Through(LogPushedToQueue::class)] final class QueueAdapter extends ComponentQueue implements Queue @@ -180,7 +181,7 @@ namespace App\Modules\EventManagement\Infrastructure\Queue; use CloudCreativity\Modules\Contracts\Messaging\Command; -final class DefaultEnqueuer +final class MyDefaultEnqueuer { public function push(Command $command): void { @@ -203,7 +204,7 @@ If neither of these two queue adapters work for you, you can write your own queu implements the port interface that is extended in your application layer: ```php -namespace CloudCreativity\Modules\Application\Ports\Queue; +namespace CloudCreativity\Modules\Contracts\Application\Ports; use CloudCreativity\Modules\Contracts\Messaging\Command; @@ -240,7 +241,7 @@ For example, a default Laravel job for queuing and dispatching commands would be ```php namespace App\Modules\EventManagement\Infrastructure\Queue; -use App\Modules\EventManagement\Application\Ports\Driving\CommandBus; +use App\Modules\EventManagement\Api\CommandBus; use CloudCreativity\Modules\Contracts\Messaging\Command; use CloudCreativity\Modules\Toolkit\Result\FailedResultException; use Illuminate\Bus\Queueable; @@ -281,7 +282,7 @@ An example of a queue job for a specific command might be: ```php namespace App\Modules\EventManagement\Infrastructure\Queue; -use App\Modules\EventManagement\Application\Ports\Driving\CommandBus; +use App\Modules\EventManagement\Api\CommandBus; use App\Modules\EventManagement\Application\UseCases\Commands\{ RecalculateSalesAtEvent\ErrorCodeEnum, RecalculateSalesAtEvent\RecalculateSalesAtEventCommand, @@ -309,7 +310,7 @@ class QueueRecalculateSalesAtEventJob implements ShouldQueue $result = $bus->dispatch($this->command); $errors = $result->errors(); - if ($errors->contains(ErrorCodeEnum::TemporaryFailure)) { + if ($errors->any(ErrorCodeEnum::TemporaryFailure)) { $this->release(now()->addSeconds(30)); return; } @@ -342,7 +343,7 @@ on the Laravel queue, and what it should do if it receives a failure result. ### Creating the Queue We can now create our queue adapter. This will extend the closure queue adapter described earlier in this chapter. For -example, to create the queue that is injected into our command bus: +example, to create the queue that is injected into our command queuer: ```php // default command queuing @@ -370,11 +371,11 @@ To apply middleware to the queue, use the `through()` method - as shown in the e the order it is added to the queue. ```php -use CloudCreativity\Modules\Infrastructure\Queue\ClosureQueue; +use App\Modules\EventManagement\Infrastructure\Queue\QueueAdapter; use CloudCreativity\Modules\Infrastructure\Queue\Middleware\LogPushedToQueue; use CloudCreativity\Modules\Toolkit\Pipeline\PipeContainer; -$queue = new ClosureQueue( +$queue = new QueueAdapter( fn: function (Command $command): void { DispatchCommandJob::dispatch($command); }, @@ -392,7 +393,7 @@ Use our `LogPushedToQueue` middleware to log a command being pushed into the que ```php use CloudCreativity\Modules\Infrastructure\Queue\Middleware\LogPushedToQueue; -$queue = new ClosureQueue( +$queue = new QueueAdapter( fn: function (Command $command): void { DispatchCommandJob::dispatch($command); }, @@ -450,7 +451,7 @@ final class MyQueueMiddleware implements QueueMiddleware :::tip If you're writing middleware that is only meant to be used for a specific command message or queue job, do not implement -the `QueueMiddleware` interface. Instead, use the same signature but change the type-hint for to the specific command +the `QueueMiddleware` interface. Instead, use the same signature but change the type-hint to the specific command message your middleware is designed for. ::: diff --git a/docs/guide/installation.md b/docs/guide/installation.md index bcc32131..f178abe8 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -18,11 +18,11 @@ composer require cloudcreativity/ddd-modules:^7.0 | `2.x` | `^8.1` | | `1.x` | `^8.1` | -> Most major upgrades are extremely easy to upgrade, as the breaking changes tend to relate to classes implemented by +> Most major version upgrades are extremely easy, as the breaking changes tend to relate to classes implemented by > the package that you are unlikely to be implementing yourself. See the [upgrade guide](./upgrade.md) for more > information. ## License -DDD Modules is licensed under the MIT license. See the +DDD Modules is licensed under the MIT licence. See the [licence file](https://github.com/cloudcreativity/php-ddd-modules/blob/main/LICENSE) for more information. diff --git a/docs/guide/toolkit/assertions.md b/docs/guide/toolkit/assertions.md index 629b91ea..f3d7e02c 100644 --- a/docs/guide/toolkit/assertions.md +++ b/docs/guide/toolkit/assertions.md @@ -19,7 +19,7 @@ final readonly class Age { if ($this->value < 18) { throw new \InvalidArgumentException( - 'Age must be greater than or equal to 0', + 'Age must be greater than or equal to 18', ); } } @@ -64,11 +64,14 @@ There are some situations where it is ok to use the `assert()` function. Here's ```php class Ticket implements Entity { + use IsEntity; + public function __construct( - private readonly Identifier $id, + Identifier $id, private ?TicketStatusEnum $status = null // ...other properties ) { + $this->id = $id; } public function getStatus(): TicketStatusEnum diff --git a/docs/guide/toolkit/identifiers.md b/docs/guide/toolkit/identifiers.md index 66d0b990..ac343a9a 100644 --- a/docs/guide/toolkit/identifiers.md +++ b/docs/guide/toolkit/identifiers.md @@ -1,6 +1,6 @@ # Identifiers -As described in the [Entities and Aggregates](../domain/entities) chapter, our domain layer must +As described in the [Entities and Aggregates](../domain/entities#identifiers) chapter, our domain layer can type-hint identifiers using an `Identifier` interface. This prevents coupling between the domain layer and the persistence layer. @@ -26,12 +26,13 @@ received: - `IntegerId` - `StringId` -- `Uuid` +- `Uuid` - plus the version-specific `UuidV4` and `UuidV7`. - `Guid` - used for polymorphism. These are described in more detail below. However, the important thing to note is that all these concrete implementations have a static `from()` method. This can be used to ensure the supplied identifier is of the correct -type. This is useful wherever you need to work with identifiers in a way the expects a specific type. +type. There is also a static `tryFrom()` method, that returns `null` instead of throwing if the identifier is not of +the expected type. This is useful wherever you need to work with identifiers in a way that expects a specific type. ## Integers @@ -55,8 +56,6 @@ class MySqlUserRepository implements UserRepository $id = $this->store($this->mapper->toDatabaseRow($entity)); $entity->setId(new IntegerId($id)); - - return $entity; } } ``` @@ -78,8 +77,6 @@ class MySqlUserRepository implements UserRepository $values['id'] = $id->value; $this->store($values); - - return $entity; } } ``` @@ -98,7 +95,7 @@ Create a string id as follows: ```php use CloudCreativity\Modules\Toolkit\Identifiers\StringId; -$id = new StringId(123); +$id = new StringId('123'); ``` :::tip @@ -117,8 +114,6 @@ class MySqlUserRepository implements UserRepository $id = $this->store($this->mapper->toDatabaseRow($entity)); $entity->setId(new StringId($id)); - - return $entity; } } ``` @@ -140,15 +135,13 @@ class MySqlUserRepository implements UserRepository $values['id'] = $id->value; $this->store($values); - - return $entity; } } ``` :::tip There may be scenarios where you map data from multiple database tables to a single entity. If these tables all use -string identifiers, there would be no way to distinguish which table the integer identifier belongs to. +string identifiers, there would be no way to distinguish which table the string identifier belongs to. In this scenario, you should use a `Guid` instead. ::: @@ -164,8 +157,13 @@ use Ramsey\Uuid\Uuid as BaseUuid; $id = new Uuid(BaseUuid::uuid4()); ``` +If you specifically need a version 4 or version 7 UUID, use the `UuidV4` or `UuidV7` classes. These can be created +via their static `make()` methods, e.g. `UuidV7::make()`. The `Uuid` class also has a static `random()` method that +returns a random `UuidV4`, and a `nil()` method that returns the nil UUID. + We also provide a `UuidFactory` which is a wrapper around the one from the `ramsey/uuid` package. It has the -same methods, but returns an instance of the `Uuid` class from this package instead. +same methods, but returns UUID identifiers from this package instead. The `uuid4()` and `uuid7()` methods return +`UuidV4` and `UuidV7` instances respectively, while the `from()` method returns the `Uuid` identifier interface. For example, in a repository you might use this as follows: @@ -183,13 +181,11 @@ class MySqlUserRepository implements UserRepository { $id = $this->uuidFactory->uuid4(); $data = $this->mapper->toDatabaseRow($entity); - $data['id'] = $id->value->toString(); + $data['id'] = $id->toString(); $this->store($data); $entity->setId($id); - - return $entity; } } ``` @@ -213,21 +209,19 @@ class MySqlUserRepository implements UserRepository $id = Uuid::from($entity->getId()); // or if we had injected the uuid factory: - $id = $this->factory->from($entity->getId()); + $id = $this->uuidFactory->from($entity->getId()); $values = $this->mapper->toDatabaseRow($entity); - $values['id'] = $id->value->toString(); + $values['id'] = $id->toString(); $this->store($values); - - return $entity; } } ``` :::tip There may be scenarios where you map data from multiple database tables to a single entity. If these tables all use -UUIDs as there primary key, in theory the chance of collision is exceptionally low. However, you may want to guarantee +UUIDs as their primary key, in theory the chance of collision is exceptionally low. However, you may want to guarantee that you can distinguish the origin of the identifier. In this case, you should use a `Guid` instead. ::: @@ -238,8 +232,8 @@ _type_ with the wrapped identifier. This is intended for scenarios where you are sources to a single entity class - and therefore using only an integer, string or UUID does not provide enough context to understand the source of the entity. -The _type_ you provide to the GUID can be anything you like. Examples would be the fully-qualified class of an Eloquent -model, or a database table name. +The _type_ you provide to the GUID can be any string or enum you like. Examples would be the fully-qualified class of an +Eloquent model, a database table name, or an enum case. GUIDs can be created using the static `fromInteger()`, `fromString()` and `fromUuid()` methods. For example: @@ -247,9 +241,9 @@ GUIDs can be created using the static `fromInteger()`, `fromString()` and `fromU use CloudCreativity\Modules\Toolkit\Identifiers\Guid; // $model is an Eloquent model -$guid = Guid::fromInteger($model::class, $model->geyKey()); -$guid = Guid::fromString($model::class, $model->geyKey()); -$guid = Guid::fromUuid($model::class, $model->geyKey()); // or provide a Ramsey UUID instance +$guid = Guid::fromInteger($model::class, $model->getKey()); +$guid = Guid::fromString($model::class, $model->getKey()); +$guid = Guid::fromUuid($model::class, $model->getKey()); // or provide a Ramsey UUID instance $guid->type === $model::class; // true ``` @@ -272,8 +266,6 @@ class MySqlUserRepository implements UserRepository UserModel::class => $this->storeUser($values), LegacyUserModel::class => $this->storeLegacyUser($values), }; - - return $entity; } } ``` diff --git a/docs/guide/toolkit/iterables.md b/docs/guide/toolkit/iterables.md index 88d127f5..509e47e3 100644 --- a/docs/guide/toolkit/iterables.md +++ b/docs/guide/toolkit/iterables.md @@ -1,3 +1,197 @@ # Iterables -TODO +Domain code often needs to work with collections of things - for example, a list of tickets held by an attendee. Using +plain PHP arrays for this is problematic. An array type-hint does not describe what the array contains, and it gives you +nowhere to put business logic that relates to the collection. + +The better approach is to write iterable classes that are specific to your domain. As described in +the [Value Objects chapter](../domain/value-objects), these classes can then encapsulate business logic specific to the +collection. + +This package provides interfaces and traits that remove the boilerplate of writing these iterable classes. The +interfaces are in the `CloudCreativity\Modules\Contracts\Toolkit\Iterables` namespace, and the traits that implement +them are in the `CloudCreativity\Modules\Toolkit\Iterables` namespace. + +| Interface | Trait | Use for | +|----------------|------------------|-------------------------------------------------| +| `ListIterator` | `IsList` | A list of values, that may be empty. | +| `NonEmptyList` | `IsNonEmptyList` | A list of values, that must never be empty. | +| `KeyedSet` | `IsKeyedSet` | A set of values that are keyed by a string. | +| `LazyList` | `IsLazyList` | A list of values that are loaded when iterated. | + +The traits store the values in a private `$stack` property (or a `$source` closure for lazy lists). Your class is +responsible for setting this property, typically in its constructor. This means your class controls exactly what types +of values can be added to it. + +## Lists + +A list is a zero-indexed collection of values. Implement the `ListIterator` interface using the `IsList` trait: + +```php +namespace App\Modules\EventManagement\Domain; + +use CloudCreativity\Modules\Contracts\Toolkit\Iterables\ListIterator; +use CloudCreativity\Modules\Toolkit\Iterables\IsList; + +/** + * @implements ListIterator + */ +final class ListOfTickets implements ListIterator +{ + /** @use IsList */ + use IsList; + + public function __construct(Ticket ...$tickets) + { + $this->stack = array_values($tickets); + } +} +``` + +The list can then be used as follows: + +```php +$tickets = new ListOfTickets($ticket1, $ticket2); + +foreach ($tickets as $ticket) { + // ... +} + +count($tickets); // 2 +$tickets->all(); // [$ticket1, $ticket2] +$tickets->isEmpty(); // false +$tickets->isNotEmpty(); // true +``` + +:::tip +Using a variadic constructor argument (`Ticket ...$tickets`) ensures every value in the list is of the correct type. We +use `array_values()` because PHP allows variadic arguments to be passed with string keys (via named arguments or +unpacking an array with string keys), and the list must be zero-indexed. +::: + +## Non-Empty Lists + +A non-empty list is a list that must always contain at least one value. This is useful for enforcing an invariant - for +example, if an attendee must always have at least one ticket. Implement the `NonEmptyList` interface using the +`IsNonEmptyList` trait: + +```php +namespace App\Modules\EventManagement\Domain; + +use CloudCreativity\Modules\Contracts\Toolkit\Iterables\NonEmptyList; +use CloudCreativity\Modules\Toolkit\Iterables\IsNonEmptyList; + +/** + * @implements NonEmptyList + */ +final class NonEmptyListOfTickets implements NonEmptyList +{ + /** @use IsNonEmptyList */ + use IsNonEmptyList; + + public function __construct(Ticket $ticket, Ticket ...$tickets) + { + $this->stack = [$ticket, ...array_values($tickets)]; + } +} +``` + +Requiring the first value as a separate constructor argument means the list can never be constructed empty. As the list +can never be empty, the `NonEmptyList` interface does not have `isEmpty()` or `isNotEmpty()` methods. + +## Keyed Sets + +A keyed set is a collection of values that are keyed by a string. Implement the `KeyedSet` interface using the +`IsKeyedSet` trait. Your class is responsible for determining the key for each value: + +```php +namespace App\Modules\EventManagement\Domain; + +use CloudCreativity\Modules\Contracts\Toolkit\Iterables\KeyedSet; +use CloudCreativity\Modules\Toolkit\Iterables\IsKeyedSet; + +/** + * @implements KeyedSet + */ +final class TicketsByReference implements KeyedSet +{ + /** @use IsKeyedSet */ + use IsKeyedSet; + + public function __construct(Ticket ...$tickets) + { + foreach ($tickets as $ticket) { + $this->stack[$ticket->reference] = $ticket; + } + } + + public function get(string $reference): ?Ticket + { + return $this->stack[$reference] ?? null; + } +} +``` + +Keyed sets have the same `all()`, `count()`, `isEmpty()` and `isNotEmpty()` methods as lists. When iterating over the +set, the keys are the string keys: + +```php +foreach ($tickets as $reference => $ticket) { + // ... +} +``` + +:::tip +The `KeyedSetOfErrors` class described in the [Results chapter](./results#keyed-error-sets) is an example of a keyed +set. +::: + +## Lazy Lists + +A lazy list does not hold its values in memory. Instead, it is given a closure that returns a generator, and the values +are only loaded when the list is iterated over. This is useful for large collections - for example, when iterating over +the results of a database query. + +Implement the `LazyList` interface using the `IsLazyList` trait. Set the `$source` property to a closure that returns a +generator: + +```php +namespace App\Modules\EventManagement\Application\Ports\Persistence; + +use Closure; +use CloudCreativity\Modules\Contracts\Toolkit\Iterables\LazyList; +use CloudCreativity\Modules\Toolkit\Iterables\IsLazyList; +use Generator; + +/** + * @implements LazyList + */ +final class LazyListOfTicketStates implements LazyList +{ + /** @use IsLazyList */ + use IsLazyList; + + /** + * @param Closure(): Generator $source + */ + public function __construct(Closure $source) + { + $this->source = $source; + } +} +``` + +The persistence adapter in the infrastructure layer can then provide a generator that loads the values on demand. For +example, using a Laravel lazy collection: + +```php +$states = new LazyListOfTicketStates(function () use ($attendeeId) { + foreach (TicketModel::where('attendee_id', $attendeeId)->lazy() as $model) { + yield $this->mapper->toTicketState($model); + } +}); +``` + +The closure is invoked each time the list is iterated over. As the values are never held in memory, a lazy list does not +implement `Countable`. If you need all the values, use the `all()` method - but be aware that this eagerly loads every +value into an array. diff --git a/docs/guide/toolkit/results.md b/docs/guide/toolkit/results.md index 92b2f042..0c52fa93 100644 --- a/docs/guide/toolkit/results.md +++ b/docs/guide/toolkit/results.md @@ -123,7 +123,8 @@ Alternatively, you can provide the `failed()` method with an error object or a l ### Error Properties -The error object provided by this package has the following properties: +The error object provided by this package has the following properties, which are accessed via the `code()`, +`message()` and `key()` methods: - `code`: an enum that identifies the error and can be used to programmatically detect and handle specific errors. It is intentionally an enum, because to programmatically detect specific errors, the codes need to be a defined list of @@ -168,7 +169,7 @@ Use the `push()` method to return a new error list with an additional error adde $errors = $errors->push(new Error(message: 'Problem 3')); ``` -You can also merge two list of errors into a new list of errors: +You can also merge two lists of errors into a new list of errors: ```php $errors3 = $errors1->merge($errors2); @@ -186,6 +187,7 @@ key. Keys can be strings or enums. To create one, provide error objects to its constructor: ```php +use CloudCreativity\Modules\Toolkit\Result\Error; use CloudCreativity\Modules\Toolkit\Result\KeyedSetOfErrors; $keyedErrors = new KeyedSetOfErrors( @@ -202,7 +204,7 @@ $keyedErrors = KeyedSetOfErrors::from($errors); ``` :::tip -There's a number of helper methods on the keyed set class - see the class for more details. +There are a number of helper methods on the keyed set class - see the class for more details. ::: ### Result Errors @@ -216,12 +218,12 @@ $errors = $result->errors(); On a successful result, the list of errors will be empty. On a failed result, there will always be at least one error. The result object also has a helper `error()` method. This returns the first error message in the list of errors, or -`null` if there are no errors with messages. This is useful when you want to provide a default error message when -handling a failed result: +`null` if there are no errors with messages. You can provide a default to the `error()` method, which is used if +there is no error message. This is useful when handling a failed result: ```php if ($result->didFail()) { - $message = $result->error() ?? 'unknown error'; + $message = $result->error('unknown error'); throw new \RuntimeException( 'Not expecting command to fail: ' . $message, ); @@ -231,18 +233,21 @@ if ($result->didFail()) { ### Detecting Errors If calling code needs to programmatically detect specific errors, you should use an enum to define the error codes that -a particular operation can return. Then you can use the `contains()` method on the list of errors to check whether a +a particular operation can return. Then you can use the `any()` method on the list of errors to check whether a specific error is present: ```php $result = $bus->dispatch($command); $errors = $result->errors(); -if ($errors->contains(CancelAttendeeTicketError::AlreadyCancelled)) { +if ($errors->any(CancelAttendeeTicketError::AlreadyCancelled)) { // handle the specific error } ``` +The list of errors also has `every()`, `find()`, `filter()` and `sole()` methods. These all accept either an enum +error code, or a closure that receives each error object. + If you only want to handle one error code at once, use the `code()` method on the errors list. This will return the first error code, or `null` if there are no error codes. ```php diff --git a/docs/guide/upgrade.md b/docs/guide/upgrade.md index 912486f7..5df5fa74 100644 --- a/docs/guide/upgrade.md +++ b/docs/guide/upgrade.md @@ -30,6 +30,11 @@ public function inactive(): bool If you use the `FakeUnitOfWork` in your tests, it now throws if `execute()` is called while it is already active. +### Command Queuer + +The deprecated `Contracts\Bus\CommandQueuer` interface has been removed. Use `Contracts\Messaging\CommandQueuer` +instead. + ## 5.x to 6.x Upgrade using Composer: @@ -38,9 +43,11 @@ Upgrade using Composer: composer require cloudcreativity/ddd-modules:^6.0 ``` -This refactor finalises our approach to structing modules, and makes some final alterations to the namespacing of +This refactor finalises our approach to structuring modules, and makes some final alterations to the namespacing of classes provided by this package. +The minimum supported PHP version is now 8.4. + ### PSR Container Usage and PHP Attributes The main exciting change in this release is we've massively simplified wiring up dispatchers and infrastructure @@ -56,10 +63,19 @@ approach. However, we recommend this approach going forward, and the documentati We've moved bus contracts and implementations to the `Contracts\Bus` and `Bus` namespaces respectively. This is to make it clearer that these are part of the bus implementation, not the application layer. While the application layer makes heavy use of these buses, messaging via buses is not an approach that needs to be confined to the application layer. For -instance, you could have an infrastructure component that uses message. +instance, you could have an infrastructure component that uses messaging. Moving these classes to their own `Bus` namespace makes this clearer. +### Messaging Namespace + +The message interfaces - `Message`, `Command`, `Query` and `IntegrationEvent` - have moved from the +`Contracts\Toolkit\Messages` namespace to the `Contracts\Messaging` namespace. + +The dispatcher interfaces that were previously in the `Contracts\Application\Ports\Driving` namespace - i.e. +`CommandDispatcher`, `CommandQueuer`, `QueryDispatcher` and `InboundEventDispatcher` - have also moved to the +`Contracts\Messaging` namespace. + ### Driven Ports All driven ports are now in the `Contracts\Application\Ports` namespace, i.e. no longer have a `Driven` sub-namespace. @@ -68,7 +84,7 @@ that are defined in the application namespace are these driven ports; hence tidy ### Event Buses -Separate middleware interfaces for the inbound and event buses, like `InboundEventMiddleware`, `OutboundEventMiddleware` +Separate middleware interfaces for the inbound and outbound event buses, like `InboundEventMiddleware`, `OutboundEventMiddleware` and `EventBusMiddleware` have been removed. These are now consolidated in an `IntegrationEventMiddleware` interface. Also, some middleware `HandleInUnitOfWork` and `LogInboundEvent` have been removed. Instead you should use the existing @@ -76,6 +92,12 @@ generic message middleware alternatives, e.g. `ExecuteInUnitOfWork` and `LogMess This removes duplication and simplifies some of the middleware to work with any type of message. +### List of Errors + +The deprecated `contains()` method has been removed from the `ListOfErrors` interface. Use `any()` instead. +Additionally, the `first()` method no longer accepts arguments. Use `find()` instead if you need to find the first error +that matches a code or closure. + ### Other Changes You might find other interfaces have moved - generally a search for the same interface name will result in you finding @@ -166,7 +188,7 @@ majority of changes. The docs have been updated to reflect all the changes in this release. If you're unsure how to upgrade something, refer to the relevant chapter in these guides for examples. -If you get stuck upgrading something, create an issue in Github so we can help. +If you get stuck upgrading something, create an issue in GitHub so we can help. ::: #### Hexagonal Architecture @@ -186,7 +208,7 @@ ports: - **Driving Ports** (aka _primary_ or _input_ ports) - interfaces that define the use cases of the bounded context. These are implemented by application services, and are used by adapters in the outside world to initiate interactions - with the application. For example, an adapter could be a HTTP controller that takes input from a request and passes it + with the application. For example, an adapter could be an HTTP controller that takes input from a request and passes it to the application via a driving port. - **Driven Ports** (aka _secondary_ or _output_ ports) - interfaces that define the dependencies of the application layer. The adapters that implement these interfaces are in the infrastructure layer. For example, a persistence port @@ -201,7 +223,7 @@ in the infrastructure layer. #### Interface Changes -The result of implementing a hexagonal infrastructure is that we've moved around interfaces to reflect this new +The result of implementing a hexagonal architecture is that we've moved around interfaces to reflect this new approach. Any interface that is a driving or driven port has been moved to the `Contracts\Application\Ports` namespace, which has @@ -254,10 +276,10 @@ The previous event bus implementation has been split in two. This is due to the inbound events is now a _driving port_, whereas publishing outbound events occurs via a _driven port_. The new inbound implementation (previously referred to as a _notifier_) is now in the `Application\InboundEventBus` -namespace. The driving port is `Contracts\Application\Ports\Driving\EventDispatcher`. +namespace. The driving port is `Contracts\Application\Ports\Driving\InboundEventDispatcher`. The new outbound implementation (referred to as a _publisher_) is now in the `Infrastructure\OutboundEventBus` -namespace. The driven port is `Contracts\Application\Ports\Driven\OutboundEvents\EventPublisher`. +namespace. The driven port is `Contracts\Application\Ports\Driven\OutboundEventPublisher`. :::tip The best approach to upgrading your event bus is to refer to the @@ -272,14 +294,14 @@ Likewise, for entities the interface is now `Contracts\Domain\Entity`. The trait - `Domain\EntityTrait` is now `Domain\IsEntity` - `Domain\EntityWithNullableIdTrait` is now `Domain\IsEntityWithNullableId`. -The identifier interface is now `Contracts\Toolkit\Identifiers\Identifier`. +The identifier interface is now `Contracts\Toolkit\Identifiers\Identifier`. ### Domain Events Domain events must now implement the `Contracts\Domain\Events\DomainEvent` interface. The method this interface defines is now `getOccurredAt()`. -The domain event dispatcher interface is now `Contracts\Events\DomainEventDispatcher`. +The domain event dispatcher interface is now `Contracts\Domain\Events\DomainEventDispatcher`. The concrete implementations of domain event dispatchers are now in the `Application\DomainEventDispatching` namespace. The application layer is the correct namespace for these dispatchers, as the domain event dispatcher interface uses the @@ -297,7 +319,7 @@ the [Domain Events chapter in the Application layer.](./application/domain-event Units of work were not previously documented. If you were using them, the best way to upgrade is to refer to the full documentation in the [Units of Work chapter.](./application/units-of-work) -This includes examples which shows the new location for the relevant interfaces. +This includes examples which show the new location for the relevant interfaces. ### Queues diff --git a/docs/index.md b/docs/index.md index 6af2b7f0..4f3a858e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -11,8 +11,8 @@ hero: text: Read the Docs link: /guide/ - theme: alt - text: View on Github - link: https://github.com/cloudcreativity/ddd-modules + text: View on GitHub + link: https://github.com/cloudcreativity/php-ddd-modules #features: # - title: Feature A