Tell, Don't Ask
When the caller reads an order's fields, checks them, and then decides what to do, the rule for that decision lives in the caller. An admin bulk-ship command copies the same if from the controller, and now the shipping rule lives in two places. When the rule changes, you have to find every copy.
Don't do this:
PHP
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\RedirectResponse;
final readonly class ShipOrderController
{
public function __invoke(Order $order): RedirectResponse
{
if ($order->status === 'paid' && $order->shipped_at === null) {
$order->status = 'shipped';
$order->shipped_at = now();
$order->save();
}
return back();
}
}Do this instead:
PHP
<?php
declare(strict_types=1);
namespace App\Models;
use App\Exceptions\OrderNotShippableException;
use Illuminate\Database\Eloquent\Model;
final class Order extends Model
{
public function markAsShipped(): void
{
if ($this->status !== 'paid' || $this->shipped_at !== null) {
throw new OrderNotShippableException($this);
}
$this->forceFill([
'status' => 'shipped',
'shipped_at' => now(),
])->save();
}
}PHP
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\RedirectResponse;
final readonly class ShipOrderController
{
public function __invoke(Order $order): RedirectResponse
{
$order->markAsShipped();
return back();
}
}The condition for shipping lives in one method, next to the data it guards. Every caller gets the same rule, and an order that cannot be shipped fails loudly instead of silently doing nothing. That failure reaches the user as a 500 unless you map OrderNotShippableException to a response, for example with a render() method on the exception. When the shipping rule changes, you change one method.