Don't Put Business Rules in Traits
The hotel gives ten percent off stays of seven nights or more. Two classes need that rule, so it went into a CalculatesPrice trait, and both the Reservation model and QuoteService use it. A trait is code PHP copies into each class that uses it at compile time, so the rule now exists as two methods on two classes. When a rate plan appears that skips the discount, the trait can only branch on something it reads through $this. A test of anything that prices a stay runs the real formula every time. The trait also needs $this->nightlyRateCents, a property it never declares and the host class has to remember to provide.
Don't do this
<?php
declare(strict_types=1);
namespace App\Traits;
use Carbon\CarbonImmutable;
trait CalculatesPrice
{
public function totalCents(CarbonImmutable $checkIn, CarbonImmutable $checkOut): int
{
$nights = (int) $checkIn->diffInDays($checkOut);
$total = $nights * $this->nightlyRateCents;
if ($nights >= 7) {
$total = (int) round($total * 0.9);
}
return $total;
}
}<?php
declare(strict_types=1);
namespace App\Services;
use App\Traits\CalculatesPrice;
final class QuoteService
{
use CalculatesPrice;
public function __construct(
private readonly int $nightlyRateCents,
) {
}
}Do this instead
Name a class after the rule and inject it into whoever needs it.
<?php
declare(strict_types=1);
namespace App\Pricing;
use Carbon\CarbonImmutable;
final readonly class NightlyRatePricing
{
public function totalCents(int $nightlyRateCents, CarbonImmutable $checkIn, CarbonImmutable $checkOut): int
{
$nights = (int) $checkIn->diffInDays($checkOut);
$total = $nights * $nightlyRateCents;
if ($nights >= 7) {
$total = (int) round($total * 0.9);
}
return $total;
}
}<?php
declare(strict_types=1);
namespace App\Services;
use App\Pricing\NightlyRatePricing;
use Carbon\CarbonImmutable;
final readonly class QuoteService
{
public function __construct(
private NightlyRatePricing $pricing,
) {
}
public function quoteCents(int $nightlyRateCents, CarbonImmutable $checkIn, CarbonImmutable $checkOut): int
{
return $this->pricing->totalCents($nightlyRateCents, $checkIn, $checkOut);
}
}The seven-night rule now lives in one file, and its inputs are the arguments of one method. The model stops pricing itself, and any class that needs a price asks for NightlyRatePricing in its constructor. A rate plan that skips the discount becomes a second class behind an interface, and the callers do not change. Traits still fit code with no business meaning, such as a logging helper shared by unrelated classes.