Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: queueable commands #6

Merged
merged 6 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@
All notable changes to this project will be documented in this file. This project adheres to
[Semantic Versioning](http://semver.org/) and [this changelog format](http://keepachangelog.com/).

## Unreleased
## Unreleased (Next Major Version)

### Added

- **BREAKING** The command bus interface now has a `queue()` method. Our command dispatcher implementation has been
updated to accept a queue factory closure as its third constructor argument. This is an optional argument, so this
change only breaks your implementation if you have manually implemented the command dispatch interface.
- The `FailedResultException` now implements the `ContextProviderInterface` to get log context from the exception's
result object. In Laravel applications, this means the exception context will automatically be logged.

### Changed

- **BREAKING** Refactored the queue implementation so that commands are queued. The queue implementation was previously
not documented. There is now complete documentation in the [Asynchronous Processing](docs/guide/infrastructure/queues)
chapter. Refer to that documentation to upgrade your implementation.
- **BREAKING** the `ResultContext` and `ObjectContext` helper classes have been moved to the `Toolkit\Loggable`
namespace.

Expand Down
66 changes: 62 additions & 4 deletions docs/guide/application/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,8 @@ class CancellationController extends Controller

$command = new CancelAttendeeTicketCommand(
attendeeId: new IntegerId((int) $attendeeId),
ticketId: new IntegerId((int) $validated->ticket),
reason: CancellationReasonEnum::from($request->reason),
ticketId: new IntegerId((int) $validated['ticket']),
reason: CancellationReasonEnum::from($request['reason']),
);

$result = $bus->dispatch($command);
Expand All @@ -305,6 +305,56 @@ to. Everything else - how your bounded context processes and responds to the act
implementation detail_ of your domain.
:::

### Queuing Commands

Commands can also be queued by the outside world. To indicate that a command should be queued, the `queue()` method is
used instead of the `dispatch()` method.

This allows the presentation and delivery layer to execute a command in a non-blocking way. For example, our controller
implementation could be updated to return a `202 Accepted` response to indicate the command has been queued:

```php
namespace App\Http\Controllers\Api\Attendees;

use App\Modules\EventManagement\BoundedContext\Application\Commands\{
CancelAttendeeTicket\CancelAttendeeTicketCommand,
EventManagementCommandBusInterface,
};
use App\Modules\EventManagement\Shared\Enums\CancellationReasonEnum;
use CloudCreativity\Modules\Toolkit\Identifiers\IntegerId;
use Illuminate\Validation\Rule;

class CancellationController extends Controller
{
public function __invoke(
Request $request,
EventManagementCommandBusInterface $bus,
string $attendeeId,
) {
$validated = $request->validate([
'ticket' => ['required', 'integer'],
'reason' => ['required', Rule::enum(CancellationReasonEnum::class)]
]);

$command = new CancelAttendeeTicketCommand(
attendeeId: new IntegerId((int) $attendeeId),
ticketId: new IntegerId((int) $validated['ticket']),
reason: CancellationReasonEnum::from($request['reason']),
);

$bus->queue($command);

return response()->noContent(status: 202);
}
}
```

:::warning
To allow commands to be queued, you **must** provide a queue factory to the command bus when creating it. This topic is
covered in the [Asynchronous Processing](../infrastructure/queues#external-queuing) chapter, with specific examples
in the _External Queuing_ section.
:::

## Middleware

Our command bus implementation gives you complete control over how to compose the handling of your commands, via
Expand All @@ -325,11 +375,12 @@ middleware to suit your specific needs.

### Setup and Teardown

Our `SetupBeforeDispatch` middleware allows your to run setup work before the command is dispatched, and optionally
Our `SetupBeforeDispatch` middleware allows setup work to be run before the command is dispatched, and optionally
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).
command. The primary use case for this is to boostrap [Domain Services](../domain/services) and to garbage collect any
singleton instances of dependencies.

For example:

Expand Down Expand Up @@ -425,6 +476,8 @@ $middleware->bind(
$this->dependencies->getLogger(),
),
);

$bus->through([LogMessageDispatch::class]);
```

The middleware will log a message before executing the command, with a log level of _debug_. It will then log a message
Expand All @@ -444,6 +497,8 @@ $middleware->bind(
dispatchedLevel: LogLevel::NOTICE,
),
);

$bus->through([LogMessageDispatch::class]);
```

#### Log Context
Expand Down Expand Up @@ -518,4 +573,7 @@ final class MyMiddleware
:::tip
If you're writing middleware that is only meant to be used for a specific command, type-hint that command instead of
the generic `CommandInterface`.

If you're writing middleware that can be used for both commands and queries, use a union type i.e.
`CommandInterface|QueryInterface`.
:::
3 changes: 3 additions & 0 deletions docs/guide/application/queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,4 +407,7 @@ final class MyMiddleware
:::tip
If you're writing middleware that is only meant to be used for a specific query, type-hint that query instead of
the generic `QueryInterface`.

If you're writing middleware that can be used for both commands and queries, use a union type i.e.
`CommandInterface|QueryInterface`.
:::
Loading