Lesson 10 of 45 · Principles of Good Object Design
Anemic Domain Model vs Rich Domain Model
The model that's just a row
Here's a class you've written, or one very much like it:
<?php
declare(strict_types=1);
namespace App\Reservations;
use Illuminate\Database\Eloquent\Model;
final class Reservation extends Model
{
protected $casts = [
'status' => ReservationStatus::class,
'check_in' => 'immutable_date',
'check_out' => 'immutable_date',
];
}That's the whole class. The Reservation model has properties (Eloquent reads them from the table's columns), it has a name, and it has nothing else. All the rules about what a reservation can do, when it can be cancelled, whether the guest can check in, whether it can be modified, when a refund applies, all of that lives somewhere else: in services, in handlers, in helpers, in jobs.
This lesson uses the Eloquent Reservation on purpose, because that is the class a Laravel codebase starts with. Its id column holds a UUID. The Repository Pattern lesson goes one step further and separates a plain Reservation from the Eloquent ReservationModel.
This is an anemic model: a database row dressed up in a class.
The other shape is a rich model: a class that owns its own state and its own rules. The data and the operations on it live in the same place.
This lesson is about the difference between the two, why anemic is so common in PHP, why rich models age better, and how to make the move without fighting the framework.
What "anemic" actually means
Martin Fowler described the "anemic domain model" anti-pattern in a 2003 post. His objection:
The fundamental horror of this anti-pattern is that it's so contrary to the basic idea of object-oriented design; which is to combine data and process together.
An anemic model is a class that has data (properties, columns, fields) and almost no behavior. Methods are mostly accessors and mutators. Anything that's actually a business rule lives in a separate "service" or "manager" class, which reads the model's state and decides what to do with it.
It looks like object-oriented code. It has classes. It has methods. But the relationship between the data and the rules is broken: the rules are all on one side of a service boundary, the data on the other, and the service has to ask the data for everything before it can decide anything.
It's the asking pattern from the Tell, Don't Ask lesson, all the way up. Anemic models are tell-don't-ask violated at the system level.
A worked example
The same use case, anemic and rich.
Anemic version:
<?php
// In a service somewhere
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Currency;
use App\Billing\Money;
use App\Payments\PaymentId;
use App\Payments\Payments;
use Illuminate\Contracts\Events\Dispatcher;
use InvalidArgumentException;
final class BookingService
{
public function __construct(
private Payments $payments,
private Dispatcher $events,
) {}
public function cancel(Reservation $reservation, string $reason): void
{
if ($reservation->status !== ReservationStatus::Confirmed) {
throw new InvalidArgumentException('Reservation is not confirmed');
}
$currency = new Currency($reservation->currency);
$freeUntil = $reservation->check_in->subHours(48);
if (now() < $freeUntil) {
$refundAmount = Money::fromCents($reservation->total_price_cents, $currency);
} else {
$refundAmount = Money::zero($currency);
}
$reservation->status = ReservationStatus::Cancelled;
$reservation->cancelled_at = now();
$reservation->cancellation_reason = $reason;
$reservation->save();
if (!$refundAmount->isZero()) {
$this->payments->refund(new PaymentId($reservation->payment_id), $refundAmount);
}
$this->events->dispatch(new ReservationCancelled(new ReservationId($reservation->id)));
}
}The service is doing the work the model should be doing. It's reading properties to make a decision. It's writing three properties and saving them. It's deciding whether the cancellation is allowed. It's deciding whether a refund applies. The model is just sitting there being mutable.
If a second service ever needs to cancel a reservation (a queue worker handling a channel manager webhook, a front-desk admin tool, a back-office cleanup job), all of that logic gets duplicated, slightly differently, and the rules drift apart.
Rich version:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Currency;
use App\Billing\Money;
use App\Reservations\Exceptions\ReservationNotConfirmed;
use DateTimeImmutable;
use Illuminate\Database\Eloquent\Model;
final class Reservation extends Model
{
private const FREE_CANCELLATION_HOURS = 48;
protected $casts = [
'status' => ReservationStatus::class,
'check_in' => 'immutable_date',
'check_out' => 'immutable_date',
'cancelled_at' => 'immutable_datetime',
];
public function cancel(string $reason, DateTimeImmutable $now): Money
{
if ($this->status !== ReservationStatus::Confirmed) {
throw new ReservationNotConfirmed(new ReservationId($this->id), $this->status);
}
$refundAmount = $this->refundAt($now);
$this->status = ReservationStatus::Cancelled;
$this->cancelled_at = $now;
$this->cancellation_reason = $reason;
return $refundAmount;
}
private function refundAt(DateTimeImmutable $now): Money
{
$currency = new Currency($this->currency);
$freeUntil = $this->check_in->subHours(self::FREE_CANCELLATION_HOURS);
if ($now < $freeUntil) {
return Money::fromCents($this->total_price_cents, $currency);
}
return Money::zero($currency);
}
}<?php
declare(strict_types=1);
namespace App\Reservations;
final readonly class CancelReservationCommand
{
public function __construct(
public ReservationId $reservationId,
public string $reason,
) {}
}<?php
// The service shrinks to orchestration
declare(strict_types=1);
namespace App\Reservations;
use App\Payments\PaymentId;
use App\Payments\Payments;
use Illuminate\Contracts\Events\Dispatcher;
use Psr\Clock\ClockInterface;
final readonly class CancelReservationCommandHandler
{
public function __construct(
private Reservations $reservations,
private Payments $payments,
private Dispatcher $events,
private ClockInterface $clock,
) {}
public function handle(CancelReservationCommand $command): void
{
$reservation = $this->reservations->withId($command->reservationId);
$refundAmount = $reservation->cancel($command->reason, $this->clock->now());
$this->reservations->save($reservation);
if (!$refundAmount->isZero()) {
$this->payments->refund(new PaymentId($reservation->payment_id), $refundAmount);
}
$this->events->dispatch(new ReservationCancelled($command->reservationId));
}
}The handler depends on Reservations, a repository interface with withId() and save(), and ReservationCancelled is a plain readonly event class the lesson doesn't show. Same outcome. Two important differences:
The rules of reservation cancellation (when it's allowed, what state changes, what refund applies) live in
Reservation, in one place, named with intent.The handler only loads, tells, saves, and reacts. It makes no decisions.
The handler can be replaced by a queue worker, an Artisan command, or a channel-manager webhook adapter with no change to the rules.
The same rich model with Doctrine
In a Symfony app, Reservation is usually a Doctrine entity: a plain PHP class that Doctrine maps to the reservations table without extending anything. The rules move over unchanged, and the fields become private:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Currency;
use App\Billing\Money;
use App\Payments\PaymentId;
use App\Reservations\Exceptions\ReservationNotConfirmed;
use DateTimeImmutable;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ORM\Table(name: 'reservations')]
final class Reservation
{
private const FREE_CANCELLATION_HOURS = 48;
#[ORM\Column(type: Types::DATETIME_IMMUTABLE, nullable: true)]
private ?DateTimeImmutable $cancelledAt = null;
#[ORM\Column(nullable: true)]
private ?string $cancellationReason = null;
public function __construct(
#[ORM\Id, ORM\Column(type: Types::GUID)]
private string $id,
#[ORM\Column(enumType: ReservationStatus::class)]
private ReservationStatus $status,
#[ORM\Column(type: Types::DATE_IMMUTABLE)]
private DateTimeImmutable $checkIn,
#[ORM\Column]
private int $totalPriceCents,
#[ORM\Column(length: 3)]
private string $currency,
#[ORM\Column]
private string $paymentId,
) {}
public function cancel(string $reason, DateTimeImmutable $now): Money
{
if ($this->status !== ReservationStatus::Confirmed) {
throw new ReservationNotConfirmed(new ReservationId($this->id), $this->status);
}
$refundAmount = $this->refundAt($now);
$this->status = ReservationStatus::Cancelled;
$this->cancelledAt = $now;
$this->cancellationReason = $reason;
return $refundAmount;
}
public function paymentId(): PaymentId
{
return new PaymentId($this->paymentId);
}
private function refundAt(DateTimeImmutable $now): Money
{
$currency = new Currency($this->currency);
$freeUntil = $this->checkIn->modify(sprintf('-%d hours', self::FREE_CANCELLATION_HOURS));
if ($now < $freeUntil) {
return Money::fromCents($this->totalPriceCents, $currency);
}
return Money::zero($currency);
}
}status, cancelledAt, and cancellationReason are private and have no setters, so cancel() is the only way to cancel a reservation, and PHP enforces it. The Eloquent version can only keep that rule by convention. The handler changes by one line: it passes $reservation->paymentId() to refund() instead of building a PaymentId from the payment_id attribute. (Doctrine accepts a final entity class when native lazy objects are enabled, which needs PHP 8.4.)
Why anemic models are so common in PHP
In PHP, the path of least resistance is an anemic model. Four reasons:
Active Record by default. Eloquent models are table rows that save themselves, and they come as mostly database mappings out of the box. The framework's tutorials show models with
$casts,$fillable, and a fewbelongsTorelationships. There's no obvious place to add behavior, so behavior goes elsewhere.The "fat model, fat controller, fat service" debate. In the PHP codebases I've worked on, the default answer is "service", which is just "we'll put the behavior in a non-model class because the model is the database".
Rails-flavored advice. "Skinny controllers, fat models" comes from Jamis Buck's 2006 post "Skinny Controller, Fat Model". In the PHP codebases I've worked on it turned into "skinny everything, except service classes, which are where work goes".
Generated setters in Symfony. Doctrine entities don't extend a base class, but MakerBundle's
make:entitycommand generates a getter for every field and a setter for every field except the id. Unless someone deletes the setters, any service can callsetStatus()and skip the rules.
None of this means anemic is necessary. Choosing rich requires deliberate effort.
Why rich models pay back
Three concrete benefits:
Cohesion at its best. Data and rules that change together live together. A new business rule about reservation cancellation doesn't have to find every service that touches reservations; it goes on
Reservation::cancel. The reader can locate every rule by reading the right model.Invariants are enforceable. A rich model can refuse to be put into an impossible state.
cancelthrows if the reservation isn't confirmed. The Value Objects lesson was this idea at the field level. Rich models are the same idea at the entity level. On an Eloquent model this only holds while callers go throughcancel(): nothing stops a service from writing$reservation->statusdirectly. A plain PHP class, like the Doctrine entity above, can keepstatusprivate so PHP enforces it.Tests get easier. Testing "does the cancellation rule do the right thing?" is testing one method on one class, not booting a service with two injected dependencies and stubbing both. No database query runs, but because
Reservationis an Eloquent model, the test extends Laravel'sTests\TestCase, not PHPUnit's plainTestCase: Eloquent asks the database connection for its date format when you setcheck_in.
"Where do the rules go in an anemic codebase?"
In practice, in services, jobs, event listeners, commands, helpers and admin scripts.
The rules don't disappear. They scatter. The same rule (with small variations) ends up in several files. Changing it means finding all of them, comparing them to figure out which one was right, and updating each of them. Some get missed. Bugs follow.
This is the same pattern as scattering business logic across delivery mechanisms (the Value Objects lesson mentioned it). Anemic models are the entity-scale version: instead of validation drifting between framework boundaries, whole business rules drift between the services that operate on the data.
Rich models without leaving the framework
A common worry is that going rich means abandoning Eloquent. It doesn't.
Practical guidance:
Keep Eloquent. Your
Reservationis still an Eloquent model. It still has columns, casts, and relationships. The framework still handles persistence. You're not building a parallel domain model from scratch.Add named methods that express business operations.
confirm,cancel,checkIn,checkOut. These are the business verbs the model now owns. The implementation can read and write the model's properties; that's fine.Make state-changing methods explicit. Change state through methods named after the operation, not by assigning attributes from outside the model. Eloquent lets any caller assign any attribute, so this is a rule the team keeps in code review.
Use value objects for typed fields. A
Reservationwith aMoney $totalPriceand aDateRange $stayDatesis much harder to put into an invalid state than one withint $total_price_centsandstring $check_in. The lessons on primitive obsession, value objects and immutable objects are direct enablers for rich models.Use enums for state machines.
ReservationStatus::Confirmed,ReservationStatus::Cancelled. Enums catch invalid states at the type level.Persist the result of operations through the repository. The handler still calls
$reservations->save($reservation)after a state-changing method. The model decides what changes; the repository handles how the change is persisted. That split keeps the framework's value while letting the model own its rules.Pass infrastructure in at call time, not via the model. Eloquent models are constructed by the framework, so you can't inject a clock or a logger through their constructor cleanly. Pass what the rule needs as a method argument:
$reservation->cancel($reason, $now), where the handler reads$nowfrom its injected clock.
This is closer to "rich Eloquent" than to a domain model with no ORM base class at all, which the Repository Pattern lesson covers. The practical middle is enough for the cancellation rule in this lesson.
Pitfalls
God models. Pushing every operation onto the model results in a class that does everything, owns everything, and changes for every reason. A Reservation that owns booking, pricing, housekeeping, payment, and audit logs is fat, not rich. Rich means owning the rules of one concept. The fix is splitting by reason to change. Coupling and cohesion and naming things by intent both apply.
Persistence concerns leaking into domain methods. A Reservation::cancel that calls $this->save() inside has tied the rule to the framework. The repository should handle saving. The model's job is to decide what state it should be in. The handler's job is to persist that state.
A rule for every table. For genuinely simple CRUD admin tools, where the domain has no rules beyond "save the record", a thin Eloquent model with a service class is fine.
The one thing to remember
If your service classes are reading three properties out of a model to decide what to do, the decision wants to live on the model. Move it. The model will have one more named method. The service will have a few fewer lines. The next person who needs to cancel a reservation, check a guest in, or apply a refund will know exactly where to look.
Related Links
- Anemic Domain ModelMartin Fowler's bliki entry naming the anti-pattern this lesson is built around, objects with data but no behavior.
- Domain ModelFowler's Patterns of Enterprise Application Architecture entry for the pattern anemic models fail to be, an object model that carries both data and behavior.
- DDD entities and ORM entitiesMatthias Noback on whether a domain entity and its ORM-mapped counterpart need to be separate classes, directly relevant to keeping models rich inside a framework.
- Objects should be constructed in one goNoback on why an object should never exist in an inconsistent state, and how to model a draft phase when it has to start incomplete.