Command Query Separation: Commands Change State, Queries Return It
A dashboard needs invoice totals and calls closeAndReport() on every page load. Each load closes the invoice again and overwrites closed_at with the time of the latest page view. A method that reads like a report mutates the database, so no one can look at the numbers without changing them.
Don't do this:
<?php
declare(strict_types=1);
namespace App\Billing;
use Carbon\CarbonImmutable;
final readonly class InvoiceService
{
public function closeAndReport(Invoice $invoice): InvoiceReport
{
$invoice->status = InvoiceStatus::CLOSED;
$invoice->closed_at = CarbonImmutable::now();
$invoice->save();
return new InvoiceReport(
total: $invoice->lineItems()->sum('amount'),
taxPaid: $invoice->lineItems()->sum('tax'),
);
}
}Do this instead:
<?php
declare(strict_types=1);
namespace App\Billing;
use Carbon\CarbonImmutable;
final readonly class CloseInvoice
{
public function handle(Invoice $invoice): void
{
$invoice->status = InvoiceStatus::CLOSED;
$invoice->closed_at = CarbonImmutable::now();
$invoice->save();
}
}<?php
declare(strict_types=1);
namespace App\Billing;
final readonly class InvoiceReportQuery
{
public function for(Invoice $invoice): InvoiceReport
{
return new InvoiceReport(
total: $invoice->lineItems()->sum('amount'),
taxPaid: $invoice->lineItems()->sum('tax'),
);
}
}The dashboard calls InvoiceReportQuery::for() on every page load and nothing is written. CloseInvoice::handle() runs only when someone closes an invoice, so it can be queued or logged without building a report as a side effect. The return type tells the caller which kind of method it is holding: void changes state, a value only reads it. A command may still return something it created, such as a new id. The rule is about not reading data back out of a write.