DEV Community

Ivan Firestone
Ivan Firestone

Posted on Originally published at blog.ifirestone.dev on

Data Objects, Concerns and Events: The Supporting Cast of a Laravel Action: 04 of 08

Data Objects, Concerns and Events: The Supporting Cast of a Laravel Action: 04 of 08

Imagine that the approval Action from the previous article stays clean for about a month. Then the product asks for four small things: email the customer, push the invoice to the ledger, write an audit entry, and ping the sales channel. Each one fits into the transaction in three lines. After four requests the Action is the new fat controller, and its signature has quietly become handle(array $data), where nobody remembers which keys are required.

An Action solves where the rule lives. It doesn't solve what feeds it, what it shares with other classes, or what it should announce to the rest of the app. Three smaller tools cover those: Data objects for input, Concerns for shared capabilities and Events for side effects. Each is easy to misuse, so this article spends as much time on where each one stops as on how it works.

The Array That Knew Too Much

An array of input has no shape. Is the key due_date or dueDate? Is notes optional? Is the quantity a string because it came from a form post? The Action can't tell you, your editor can't either, and a typo fails at runtime in production.

A Data object gives the input a name and a type. In modern PHP that is a readonly class:

final readonly class IssueInvoiceData
{
    /** @param list<InvoiceLineData> $lines */
    public function __construct(
        public int $customerId,
        public CarbonImmutable $dueDate,
        public array $lines,
        public ?string $notes = null,
    ) {}

    public static function fromRequest(StoreInvoiceRequest $request): self
    {
        $input = $request->validated();

        return new self(
            customerId: (int) $input['customer_id'],
            dueDate: CarbonImmutable::parse($input['due_date']),
            lines: array_map(InvoiceLineData::fromArray(...), $input['lines']),
            notes: $input['notes'] ?? null,
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

The (int) cast is there on purpose. Form posts deliver strings, and the Data object is the one place that converts them. InvoiceLineData is another readonly class built the same way. Readonly classes need PHP 8.2 or later.

Now the Action asks for what it needs, and every caller has to supply it:

public function handle(IssueInvoiceData $data, User $author): Invoice

Enter fullscreen mode Exit fullscreen mode

The same object works from a controller, a console import, a queued job payload or a test, with no copy of the mapping logic.

There are limits. A Data object holds data and the shape of data. It doesn't query the database, apply business rules or carry Eloquent models around. And it is overkill for a method with two scalar arguments: ApproveInvoice doesn't need one. Packages such as spatie/laravel-data automate the mapping, and they are worth a look once writing fromRequest by hand starts to hurt. Plain readonly classes are enough until then.

What a Concern Is For

Laravel itself puts shared model behavior in a Concerns namespace, and the habit is worth copying. A Concern is a trait that gives many classes the same small capability. The tenant article had a good one, BelongsToCompany: it attaches a scope, fills a column, and applies to every tenant-owned model. Another might be:

trait Archivable
{
    public function scopeActive(Builder $query): void
    {
        $query->whereNull('archived_at');
    }

    public function archive(): void
    {
        $this->forceFill(['archived_at' => now()])->save();
    }
}

Enter fullscreen mode Exit fullscreen mode

A quick test tells you whether something is a Concern. Can you name it as a capability, with a prefix like Has, Belongs or an adjective such as Archivable? If the best name you can find is HandlesInvoiceApproval, it is an Action wearing a trait.

The failure mode is the junk drawer. A 3,000-line model split into eight traits is still a 3,000-line model, only harder to read, because the methods are in eight files and each trait quietly assumes columns that live somewhere else. Three costs to watch:

  • Hidden coupling: the trait uses $this->status without declaring it needs one.
  • Name collisions between methods of different traits.
  • Tests that only work through a model that uses the trait.

Keep Concerns small, capability-shaped and boring.

Events for the Things the Action Shouldn't Know About

Back to the four requests. Sending the email, updating the ledger and pinging the channel are reactions to a fact: an invoice was approved. The Action doesn't need to know who reacts. It announces the fact, and whoever cares listens.

A useful split: what must succeed or fail together with the approval stays inside the Action's transaction. What can happen later, or fail on its own, becomes a listener. The email is a listener. The status change is not.

final class InvoiceApproved implements ShouldDispatchAfterCommit
{
    use Dispatchable;

    public function __construct(
        public readonly int $invoiceId,
        public readonly int $companyId,
    ) {}
}

Enter fullscreen mode Exit fullscreen mode

The ShouldDispatchAfterCommit interface matters. Per the Laravel events docs, such an event isn't dispatched until the open database transaction commits, and it is discarded if the transaction fails. Without it, a queued listener could run before the commit, or send an email for an approval that was rolled back.

The Action dispatches it from inside the transaction, with ids rather than models, so the payload is small and explicit:

InvoiceApproved::dispatch($invoice->id, $invoice->company_id);

Enter fullscreen mode Exit fullscreen mode

The listener is where the tenant article comes back. A queued listener runs in a worker, with no URL and no user, so under a fail-closed scope it has no company. The fix is the job middleware we already know, which listeners support too. This version takes the id in its constructor, because a listener can't read it off the job the way the earlier example did:

final class RunsAsCompany
{
    public function __construct(private int $companyId) {}

    public function handle(object $job, Closure $next): void
    {
        app(TenantContext::class)->runAs($this->companyId, fn () => $next($job));
    }
}

final class SendApprovalEmail implements ShouldQueue
{
    public function middleware(InvoiceApproved $event): array
    {
        return [new RunsAsCompany($event->companyId)];
    }

    public function handle(InvoiceApproved $event): void
    {
        $invoice = Invoice::findOrFail($event->invoiceId);

        Mail::to($invoice->customer->email)->send(new InvoiceApprovedMail($invoice));
    }
}

Enter fullscreen mode Exit fullscreen mode

The docs show the middleware method on a listener receiving the event as its argument, which is what makes this work. Laravel discovers listeners by scanning the Listeners directory for handle methods with a type-hinted event, so there is no registration step. When you want to see the wiring, php artisan event:list prints it.

The whole path now looks like this:

Data Objects, Concerns and Events: The Supporting Cast of a Laravel Action: 04 of 08

What This Costs You

Events trade clarity for decoupling, and the bill arrives in four places:

  • Hidden flow. Someone reading ApproveInvoice can't see the email. Name events in the past tense, keep listeners few, and use event:list. An event with one listener and no prospect of a second is a method call in disguise.
  • Eventual consistency. The email arrives after the response, and the ledger may lag. The UI has to tolerate that.
  • Listeners can run twice. Queues retry. Make each listener idempotent, so that a second email or a second ledger row isn't possible.
  • Testing in two parts. Fake the event in the Action's test (Event::fake([InvoiceApproved::class])) and test each listener on its own.

Data objects cost a class per use case. Concerns cost readability the moment they multiply. None of the three is free, and none is needed on day one.

Conclusion

The Action that was drifting toward handle(array $data) now takes a typed object, leaves its capabilities to small Concerns, and announces what happened instead of doing everyone's chores. What changed isn't the amount of code. It's that each piece has a reason to exist and a reason to stop.

For today: find one Action with an array argument and give it a Data object, and find one trait whose name is a verb phrase and ask whether it is really an Action. The last article in the series steps back from the code and looks at the order in which a project like this actually gets built and shipped.

Top comments (0)