Lesson 15 of 45 · Wiring Things Together
The Repository Pattern
A contested pattern in PHP
If you ask ten PHP developers about the Repository Pattern, you'll get four answers. Some will tell you it's essential. Some will tell you it's overkill in Laravel because Eloquent already does what a repository does. Some will tell you it's the only honest way to decouple business code from persistence. Some will tell you it's just a wrapper that adds files for nothing.
All of them have a point. The pattern's reputation is contested because much of what gets called "the Repository Pattern" in the Laravel codebases I've worked on isn't one. The pattern has a real definition with real benefits, and it has a thousand naive implementations that share the name without sharing the value.
What a repository actually is
The Repository entry in Martin Fowler's Patterns of Enterprise Application Architecture (2002), credited on his catalog page to Edward Hieatt and Rob Mee, defines it like this:
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
The two important phrases: collection-like interface and domain objects.
The repository should look, from the outside, like an in-memory collection of domain entities. You ask it for things in business terms ("guests who haven't logged in for 30 days", "the reservation with this id"), and it gives you domain objects back. Whether it's reading from MySQL, Postgres, MongoDB, an in-memory array, or a remote API is hidden. The caller doesn't know and doesn't care.
The naive version
Here's what often gets called "Repository Pattern" in Laravel codebases:
<?php
declare(strict_types=1);
namespace App\Reservations;
use Illuminate\Database\Eloquent\Collection;
final class ReservationRepository
{
public function find(int $id): ?Reservation
{
return Reservation::find($id);
}
public function all(): Collection
{
return Reservation::all();
}
public function create(array $data): Reservation
{
return Reservation::create($data);
}
public function update(Reservation $reservation, array $data): Reservation
{
$reservation->update($data);
return $reservation;
}
public function delete(Reservation $reservation): void
{
$reservation->delete();
}
}This is a thin wrapper around Eloquent. Everything it does, you could do directly with Reservation::find($id) and Reservation::all(). The wrapper adds:
A class file.
A handful of methods that forward calls.
It doesn't decouple anything (the methods take and return Eloquent models). It doesn't enable testing (the methods still hit the database). It doesn't shape the API around the domain (it shapes it around CRUD). The "repository" exists, but the pattern doesn't.
This is the version I see most often, and it's the reason the pattern has a bad reputation in the Laravel community.
Symfony has its own version. make:entity generates a repository next to each Doctrine entity, and the repository extends ServiceEntityRepository. Add one query method and it looks like this:
<?php
declare(strict_types=1);
namespace App\Reservations;
use DateTimeImmutable;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Reservation>
*/
class ReservationRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Reservation::class);
}
/**
* @return list<Reservation>
*/
public function confirmedArrivalsOn(DateTimeImmutable $date): array
{
return $this->createQueryBuilder('r')
->where('r.status = :status')
->andWhere('r.checkIn = :date')
->setParameter('status', ReservationStatus::Confirmed)
->setParameter('date', $date, Types::DATE_IMMUTABLE)
->getQuery()
->getResult();
}
}This one is closer to the real thing. The method has a business name, and Reservation is a plain Doctrine entity. The leak is what the class inherits: find, findAll, findBy, findOneBy and count are all public. Any service that receives ReservationRepository can write findBy(['status' => ReservationStatus::Confirmed]) and skip confirmedArrivalsOn, so queries end up written wherever they're needed, the same problem as with the Eloquent wrapper.
The good example
A real repository is a domain-shaped interface with a persistence implementation hidden behind it.
<?php
// In your business code
declare(strict_types=1);
namespace App\Reservations;
use App\Booking\RoomId;
use DateTimeImmutable;
interface Reservations
{
public function withId(ReservationId $id): Reservation;
public function existingFor(RoomId $roomId, DateRange $stayDates): ReservationCollection;
public function save(Reservation $reservation): void;
public function pendingCheckInsOn(DateTimeImmutable $date): ReservationCollection;
}Fowler's definition says collection-like, yet the interface has save. Vaughn Vernon (Implementing Domain-Driven Design, chapter 12) calls this a persistence-oriented repository: you save after each change, instead of adding an object once and letting the ORM track it from then on. Eloquent has no unit of work that tracks changed objects, so something has to call save, and the save-based shape is the usual one in PHP.
Reservations is the repository. The two query methods hand back a ReservationCollection, a plain class in the business code:
<?php
declare(strict_types=1);
namespace App\Reservations;
use ArrayIterator;
use Countable;
use IteratorAggregate;
/**
* @implements IteratorAggregate<int, Reservation>
*/
final readonly class ReservationCollection implements IteratorAggregate, Countable
{
/** @var list<Reservation> */
private array $reservations;
public function __construct(Reservation ...$reservations)
{
$this->reservations = array_values($reservations);
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->reservations);
}
public function count(): int
{
return count($this->reservations);
}
public function isEmpty(): bool
{
return $this->reservations === [];
}
}Laravel's Collection or Doctrine's ArrayCollection would do the same job, but either one puts the framework back into the business interface. The variadic constructor makes PHP reject anything that isn't a Reservation, and no caller can add to the list after the repository returns it. Jeff Bay's Object Calisthenics rules call this a first-class collection. It has no domain rules yet. When a rule about a list of reservations shows up, such as the total nights across a guest's stays, it goes here instead of in whichever service needs it first.
<?php
// In your infrastructure code
declare(strict_types=1);
namespace App\Reservations\Infrastructure;
use App\Booking\RoomId;
use App\Reservations\DateRange;
use App\Reservations\Exceptions\ReservationNotFound;
use App\Reservations\Models\ReservationModel;
use App\Reservations\Reservation;
use App\Reservations\ReservationCollection;
use App\Reservations\ReservationId;
use App\Reservations\Reservations;
use App\Reservations\ReservationStatus;
use DateTimeImmutable;
final readonly class EloquentReservations implements Reservations
{
public function withId(ReservationId $id): Reservation
{
$row = ReservationModel::query()->find($id->value);
if ($row === null) {
throw new ReservationNotFound($id);
}
return Reservation::reconstitute($row->getAttributes());
}
public function existingFor(RoomId $roomId, DateRange $stayDates): ReservationCollection
{
$rows = ReservationModel::query()
->where('room_id', $roomId->value)
->where('check_in', '<', $stayDates->checkOut)
->where('check_out', '>', $stayDates->checkIn)
->get();
return new ReservationCollection(
...$rows->map(fn(ReservationModel $row) => Reservation::reconstitute($row->getAttributes()))->all(),
);
}
public function save(Reservation $reservation): void
{
$row = ReservationModel::query()->find($reservation->id->value)
?? new ReservationModel();
$row->forceFill([
'id' => $reservation->id->value,
'guest_id' => $reservation->guestId->value,
'room_id' => $reservation->roomId->value,
'check_in' => $reservation->stayDates->checkIn->format('Y-m-d'),
'check_out' => $reservation->stayDates->checkOut->format('Y-m-d'),
'adults' => $reservation->guestCount->adults,
'children' => $reservation->guestCount->children,
'price_cents' => $reservation->quotedPrice->amountInCents,
'currency' => $reservation->quotedPrice->currency->isoCode,
'status' => $reservation->status()->value,
]);
$row->save();
}
public function pendingCheckInsOn(DateTimeImmutable $date): ReservationCollection
{
$rows = ReservationModel::query()
->where('status', ReservationStatus::Confirmed->value)
->whereDate('check_in', $date)
->get();
return new ReservationCollection(
...$rows->map(fn(ReservationModel $row) => Reservation::reconstitute($row->getAttributes()))->all(),
);
}
}Reservation::reconstitute() is the named constructor from the Named Constructors lesson that rebuilds a reservation from a row. getAttributes() hands it the raw column values, which it parses itself. save goes the other way and flattens each value object back into its columns. That translation between ReservationModel and the plain Reservation is the work the naive version skips. Two things changed compared to the naive version:
The interface is named in domain terms.
withId,existingFor,pendingCheckInsOn. Notfind,findBy,where. The methods read like sentences a product manager would use.The interface deals in domain types. It returns
Reservation(a plain PHP class that knows nothing about Eloquent), notReservationModel(the Eloquent class). The Eloquent model is an implementation detail ofEloquentReservations. Business code doesn't import it.
This goes one step further than the Anemic Domain Model vs Rich Domain Model lesson, where Reservation stayed an Eloquent model: here a plain Reservation is separate from the Eloquent ReservationModel.
In a Symfony app, the same interface gets a Doctrine implementation. It wraps the entity manager instead of extending ServiceEntityRepository, so only the four methods of Reservations are public:
<?php
declare(strict_types=1);
namespace App\Reservations\Infrastructure;
use App\Booking\RoomId;
use App\Reservations\DateRange;
use App\Reservations\Exceptions\ReservationNotFound;
use App\Reservations\Reservation;
use App\Reservations\ReservationCollection;
use App\Reservations\ReservationId;
use App\Reservations\Reservations;
use App\Reservations\ReservationStatus;
use DateTimeImmutable;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityManagerInterface;
final readonly class DoctrineReservations implements Reservations
{
public function __construct(private EntityManagerInterface $entityManager) {}
public function withId(ReservationId $id): Reservation
{
return $this->entityManager->find(Reservation::class, $id->value)
?? throw new ReservationNotFound($id);
}
public function existingFor(RoomId $roomId, DateRange $stayDates): ReservationCollection
{
$reservations = $this->entityManager->createQueryBuilder()
->select('r')
->from(Reservation::class, 'r')
->where('r.roomId = :roomId')
->andWhere('r.checkIn < :checkOut')
->andWhere('r.checkOut > :checkIn')
->setParameter('roomId', $roomId->value)
->setParameter('checkIn', $stayDates->checkIn, Types::DATE_IMMUTABLE)
->setParameter('checkOut', $stayDates->checkOut, Types::DATE_IMMUTABLE)
->getQuery()
->getResult();
return new ReservationCollection(...$reservations);
}
public function save(Reservation $reservation): void
{
$this->entityManager->persist($reservation);
$this->entityManager->flush();
}
public function pendingCheckInsOn(DateTimeImmutable $date): ReservationCollection
{
$reservations = $this->entityManager->createQueryBuilder()
->select('r')
->from(Reservation::class, 'r')
->where('r.status = :status')
->andWhere('r.checkIn = :date')
->setParameter('status', ReservationStatus::Confirmed)
->setParameter('date', $date, Types::DATE_IMMUTABLE)
->getQuery()
->getResult();
return new ReservationCollection(...$reservations);
}
}Here Reservation is the Doctrine entity from the Anemic Domain Model vs Rich Domain Model lesson, with the roomId and checkOut fields that lesson trimmed. There is no mapping code. Doctrine is a Data Mapper: it maps the plain Reservation to its table itself, so the translation EloquentReservations writes by hand comes with the ORM.
The handler that uses either implementation runs once a day and marks yesterday's confirmed arrivals that never checked in:
<?php
declare(strict_types=1);
namespace App\Reservations;
use Psr\Clock\ClockInterface as Clock;
final readonly class MarkNoShowsCommandHandler
{
public function __construct(
private Reservations $reservations,
private Clock $clock,
) {}
public function handle(): void
{
$now = $this->clock->now();
$yesterday = $now->modify('-1 day');
foreach ($this->reservations->pendingCheckInsOn($yesterday) as $reservation) {
$reservation->markNoShow($now);
$this->reservations->save($reservation);
}
}
}Reservation::markNoShow(DateTimeImmutable $now) moves the status to NoShow and records a ReservationMarkedNoShow event. The handler depends on Reservations (the interface). It doesn't know whether the implementation is Eloquent or Doctrine. It doesn't import any framework class. It speaks in domain verbs.
What you actually get
The real version of the pattern earns its place by giving you five things the naive wrapper doesn't:
Testability without the database. A test can use
InMemoryReservations implements Reservationsand run without a database, fast, in pure PHP. The handler doesn't notice. With the naive wrapper, every test is an integration test, slower and flakier. The Test Doubles lesson buildsInMemoryReservationsin full, with a contract test that runs the same assertions against it andEloquentReservations.Business-shaped queries. "Reservations overlapping this stay" is a domain concept named in domain terms. The query lives in one place. Every caller asks the same question the same way. With ad-hoc Eloquent calls scattered through services, the same logic appears in several places, each slightly different, until somebody changes one and forgets the others.
Framework decoupling. The handler talks to
Reservations, an interface owned by the business code. The Eloquent implementation lives in infrastructure. Switching to Doctrine, to a remote API, or to in-memory for tests is a new implementation and one binding change. Replacing the whole production data source is rare, and it isn't the main payoff; the swap you make every day isInMemoryReservationsin tests. Without the pattern, the framework is in the middle of every business operation.Domain entities, not database rows. With a real repository, the rest of the codebase deals in
Reservation(rich, behavior-owning, validated). Without it, the rest of the codebase deals inReservationModel(an ActiveRecord wrapper around a row).Room for decorators. Because callers depend on the
Reservationsinterface, another class can implement the same interface and wrap the real one: aLoggingReservationsthat records how long each query takes, or a cache in front of a read-heavy query. The container hands the handler the wrapper, and neither the handler norEloquentReservationschanges. This is the Decorator Pattern. The naiveReservationRepositoryis afinalclass with no interface, so adding logging to it means editing it.
Moving part of the data to a different store happens more often than replacing the whole data source. I've worked on projects where one moved part of its data from MySQL to Elasticsearch and another to OpenSearch, because that data loaded faster in a store built for its type and scale. Neither codebase had repositories, so the queries for that data were spread through the code. The teams spent months rewriting every query that touched it and testing the result before it reached production. Behind a repository interface, the same move is a new implementation, bound to the interface for that part of the app.
The Eloquent objection
A common pushback in Laravel: "Eloquent already lets me do Reservation::where(...)->get(). Why add a repository?"
The objection is fair on its face and ignores three real costs:
Reservation::where(...)is a global query that any code, anywhere, can write. There's no central place where queries live, no guarantee that the same question is asked the same way, and no way to test code without a database or a mocked query builder.Eloquent models conflate domain and persistence. A model that has business methods, persistence methods, query scopes, mutators, and accessors all on one class is hard to test without the database. The repository pattern lets you split them: the domain
Reservationlives in business code, the EloquentReservationModellives in infrastructure, the repository is the bridge.Direct Eloquent calls are framework coupling. Every place that does
ReservationModel::query()->where(...)is a place that imports Eloquent into business code.
For a small Laravel project, the cost of these may not justify a repository. For a long-lived product, they can.
When repositories earn their place
The pattern isn't free, and not every project needs it.
It earns its place when:
The product is long-lived and the cost of upgrading the framework matters.
The team is large enough that "where do these queries live?" is a real question.
The domain has rich entities that genuinely differ from the database row shape.
Tests need to be fast and the database is too slow to involve in most of them.
More than one delivery mechanism (HTTP, queue, console, webhook) needs to ask the same questions.
It doesn't earn its place when:
The project is a small CRUD admin tool, where the database row is the domain object.
The team is one or two people and the indirection cost outweighs the decoupling benefit.
The "domain" is genuinely just a thin layer over the schema.
Context decides everything, and the pattern is a tool, not a rule.
A note on the Specification Pattern
A common follow-up question: "what about complex queries that compose, like reservations that are confirmed AND check in today AND have outstanding balance?"
That's the Specification Pattern, covered later in this course. Specifications let you build query criteria as composable objects that the repository can interpret. They're a useful companion to repositories when the queries get genuinely combinatorial. A few well-named methods on the repository (confirmedCheckInsTodayWithBalance) are simpler and cheaper. Reach for specifications when the methods on the repository start to multiply uncontrollably.
Pitfalls
A few common mistakes:
Generic CRUD methods. A repository with find, all, where, create, update, delete is the naive wrapper. Methods should be named after the questions the business asks, not the operations the database supports. In Symfony, extending ServiceEntityRepository adds find, findBy and the rest to the class. Implementing Reservations on that subclass and type-hinting the interface keeps callers away from them. Injecting EntityManagerInterface, as DoctrineReservations does, removes them altogether, and the entity no longer needs a repositoryClass pointing back at its repository. A common variant keeps $entityManager->getRepository(Reservation::class) in a private property and calls findBy on it inside the class.
Returning the ORM model. A repository whose methods return ReservationModel (the Eloquent class) hasn't decoupled anything. The model is now traveling through every layer of the application. Map to a domain entity before returning. The mapping logic is the cost of the pattern; it's also the value.
One repository per table. Repositories are organized around aggregates (a cluster of objects that must stay consistent together, saved as one unit), not tables. A Reservations repository might cover the reservations table, the reservation_charges table, and the reservation_notes table, because all three belong to one consistent reservation concept. Splitting by table breaks the abstraction.
Repositories with dozens of methods. A Reservations repository with twenty query methods is a sign that either the queries are too granular (combine some) or there are really two aggregates hiding inside one (split it). Coupling and cohesion and SRP both apply.
Using the repository for screens and reports. A repository loads whole entities so business code can change them. A page listing 50 reservations with guest names changes nothing, so loading and mapping 50 full Reservation objects to render a table is wasted work. Query the data straight into a small read DTO and keep the repository for the write side. pendingCheckInsOn stays, because the handler changes every reservation it returns. Matthias Noback's Read with the author app splits it this way: SessionRepository has three methods for the write side, and the screens read SessionForMember DTOs through a separate Sessions interface implemented with plain DBAL queries. That split is the core of CQRS (separate models for reads and writes), which the Building Maintainable PHP Applications: CQRS and Event Sourcing course covers.
Calling the repository inside the entity. A Reservation that calls $this->reservations->save(...) from inside one of its methods has tied itself to its own persistence. The handler should be the one calling save, not the entity. The Anemic Domain Model vs Rich Domain Model lesson's note about "persistence concerns leaking into domain methods" applies directly.
The one thing to remember
A real repository looks like a collection of domain objects, named in domain terms, and hides persistence behind itself. A thin wrapper around Eloquent that exposes find/all/where/update is just a class with extra steps. The difference is whether you can read the interface and tell what the business does, without knowing which data source is underneath.
When you find query logic scattered across services, business code importing Eloquent, or tests that have to boot the framework to ask a simple question, the repository pattern is the cleanup to consider.
Related Links
- Repository (Martin Fowler)The PoEAA catalog entry for the Repository pattern (by Edward Hieatt and Rob Mee), the collection-like interface this lesson quotes directly.
- Key Design Patterns (Matthias Noback)A free book chapter covering repositories, entities, and application services together, useful for seeing how the pieces fit around each other.
- Working with Objects (Doctrine ORM Docs)Doctrine's docs on EntityRepository and custom repositories, a real example of query methods grouped by domain concept instead of by table.
- Repositories and their true purpose (Muhammed Sarı)Argues that swapping the data source is a minor bonus and that a repository's job is to be the authoritative collection for write models, with read models going straight to the data source.
- How to use Repository with Doctrine as Service in Symfony (Tomas Votruba)The case for injecting the entity manager instead of extending Doctrine's repository class. Some of its complaints predate ServiceEntityRepository; the ones about inherited untyped findBy and the entity pointing at its repository still hold.
- Read with the author (Matthias Noback)A small Symfony app with a three-method write-side repository, an in-memory fake, a contract test, and a separate DBAL read model for its screens.
- Specification Pattern (Wikipedia)An overview of the Specification pattern this lesson references as a companion for filtering by business rules.