The Repository Pattern

The Repository Pattern in PHP: --- A large company never lets its office staff wander into the warehouse to rummage among the shelves.


The Analogy: The Warehouse Despatch Counter

A large company never lets its office staff wander into the warehouse to rummage among the shelves. Instead there is a despatch counter with a clerk. Staff hand the clerk a request slip -- "I need part number 4471" or "give me every item in the electrical category" -- and the clerk goes into the warehouse, finds the goods, and hands them back over the counter. The office staff never see the shelving layout, the aisle numbers, or whether the stock is kept on pallets or in bins. They know only the counter and the slips it accepts. A repository is that despatch counter: a single place that turns plain business requests into whatever storage operations are actually needed, hiding the warehouse behind it.

The power of the counter is that the warehouse behind it can change completely without the office noticing. Today the goods sit on physical shelves; tomorrow the company switches to an automated storage system, or a temporary rented unit across town. As long as the counter still accepts the same slips and hands back the same goods, not one person in the office has to change how they work. A repository behind an interface gives you exactly this: the code that asks for a user by id neither knows nor cares whether the user comes from a MySQL database, a JSON file, or an in-memory list built for a test.

The slips the counter accepts are written in the language of the business, not the warehouse. Nobody hands over a slip saying "run this shelf-scanning routine on aisle 12"; they say "find the customer named Ada". The clerk translates that intent into shelf operations. A repository's methods are named for what the application wants -- findByEmail, save, allActive -- not for the SQL underneath. This keeps the calling code readable and focused on business meaning rather than storage mechanics.

The failure mode is the counter that quietly leaks the warehouse. If the clerk starts handing back slips that only make sense if you know the aisle numbering, or requires callers to phrase requests in shelf-coordinates, the abstraction has broken: the office is now coupled to the warehouse layout after all. In code this happens when a repository returns raw database result arrays with column names baked in, or exposes a method that only a particular database could satisfy. The moment the calling code depends on those details, swapping the storage becomes impossible, and the counter was pointless. A repository is only as valuable as the storage details it manages to keep hidden.


Syntax or Core Structure

A repository is defined by an interface stating what operations the application needs, and a concrete class implementing it against a real store. The interface speaks in business terms; the implementation holds the SQL.

<?php
declare(strict_types=1);

interface UserRepository {
    public function save(string $name, string $email): int;
    public function find(int $id): ?array;
    public function all(): array;
}

final class PdoUserRepository implements UserRepository {
    public function __construct(private PDO $pdo) {
        $this->pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
    }
    public function save(string $name, string $email): int {
        $s = $this->pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
        $s->execute([$name, $email]);
        return (int) $this->pdo->lastInsertId();
    }
    public function find(int $id): ?array {
        $s = $this->pdo->prepare('SELECT id, name, email FROM users WHERE id = ?');
        $s->execute([$id]);
        $row = $s->fetch(PDO::FETCH_ASSOC);
        return $row === false ? null : $row;
    }
    public function all(): array {
        return $this->pdo->query('SELECT id, name FROM users ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
    }
}

$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$repo = new PdoUserRepository($pdo);
$id = $repo->save('Ada', 'ada@x.com');
echo "saved id: $id\n";
$u = $repo->find($id);
echo 'found: ', $u['name'], ' / ', $u['email'], "\n";
echo 'missing: ', var_export($repo->find(99), true), "\n";

Output:

saved id: 1
found: Ada / ada@x.com
missing: NULL

The UserRepository interface declares three intent-named methods. PdoUserRepository implements them with prepared statements, receiving its PDO by injection so it never opens its own connection. Saving Ada returns id 1, finding that id returns her row, and finding a non-existent id returns null rather than false -- a cleaner "not found" signal that var_export prints as NULL. Every caller works through the interface, not the SQL.


Technical Depth: Swappable Backends and Entity Mapping

Depending on the interface, not the class

The chief benefit of a repository is that code depending on the interface can be handed any implementation. For tests you supply a fast in-memory fake; in production you supply the database-backed one. Neither the calling code nor its logic changes.

ConcernInterfacePdo... implementationInMemory... implementation
SpeaksBusiness intentSQL over PDOPlain arrays
Used inEverywhereProductionTests
Needs a databaseNoYesNo
<?php
declare(strict_types=1);

interface UserRepository {
    public function save(string $name, string $email): int;
    public function find(int $id): ?array;
}

final class InMemoryUserRepository implements UserRepository {
    private array $rows = [];
    private int $next = 1;
    public function save(string $name, string $email): int {
        $id = $this->next++;
        $this->rows[$id] = ['id' => $id, 'name' => $name, 'email' => $email];
        return $id;
    }
    public function find(int $id): ?array {
        return $this->rows[$id] ?? null;
    }
}

function greet(UserRepository $repo, int $id): string {
    $u = $repo->find($id);
    return $u === null ? 'unknown' : "hello {$u['name']}";
}

$repo = new InMemoryUserRepository();
$a = $repo->save('Ada', 'ada@x.com');
$b = $repo->save('Ben', 'ben@x.com');
echo greet($repo, $a), "\n";
echo greet($repo, $b), "\n";
echo greet($repo, 99), "\n";

Output:

hello Ada
hello Ben
unknown

The greet function accepts any UserRepository. Here it receives an in-memory fake that stores rows in an array and assigns ids from a counter, with no database at all. Ada and Ben greet by name, and id 99 -- absent -- yields unknown because find returns null. In a real test suite this fake makes the logic testable in microseconds, and swapping in PdoUserRepository for production requires changing only the wiring, never greet.

Mapping rows to entity objects

Returning raw associative arrays works, but it leaks column names into every caller. A stronger repository maps each row to a typed entity object, so callers get real properties and methods, with the column-to-property translation confined to one private method.

<?php
declare(strict_types=1);

final class Product {
    public function __construct(
        public readonly int $id,
        public readonly string $name,
        public readonly int $cents,
    ) {}
    public function price(): string {
        return number_format($this->cents / 100, 2);
    }
}

final class ProductRepository {
    public function __construct(private PDO $pdo) {
        $this->pdo->exec('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, cents INTEGER)');
    }
    public function add(string $name, int $cents): Product {
        $s = $this->pdo->prepare('INSERT INTO products (name, cents) VALUES (?, ?)');
        $s->execute([$name, $cents]);
        return new Product((int) $this->pdo->lastInsertId(), $name, $cents);
    }
    private function map(array $row): Product {
        return new Product((int) $row['id'], $row['name'], (int) $row['cents']);
    }
    public function all(): array {
        $rows = $this->pdo->query('SELECT id, name, cents FROM products ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
        return array_map([$this, 'map'], $rows);
    }
}

$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$repo = new ProductRepository($pdo);
$repo->add('Widget', 1250);
$repo->add('Gadget', 500000);

foreach ($repo->all() as $p) {
    echo $p->name, ': ', $p->price(), "\n";
}

Output:

Widget: 12.50
Gadget: 5,000.00

The private map method is the single point where column names like cents turn into constructor arguments, so if the schema renames a column only map changes. Callers receive Product objects and call price(), which formats cents as currency -- note that number_format adds a thousands separator, so 500000 cents prints as 5,000.00. The column names never escape the repository, which is exactly the leak the pattern exists to prevent.


Real World Example: A Checkout Service Over a Repository

A Checkout service places the items in a cart and reports the total units ordered. It depends only on an OrderRepository interface, so the very same service runs against a real database in production and an in-memory fake in tests -- with identical results and no code change.

<?php
declare(strict_types=1);

interface OrderRepository {
    public function place(string $sku, int $qty): int;
    public function totalUnits(): int;
}

final class PdoOrderRepository implements OrderRepository {
    public function __construct(private PDO $pdo) {
        $this->pdo->exec('CREATE TABLE orders (id INTEGER PRIMARY KEY, sku TEXT, qty INTEGER)');
    }
    public function place(string $sku, int $qty): int {
        $s = $this->pdo->prepare('INSERT INTO orders (sku, qty) VALUES (?, ?)');
        $s->execute([$sku, $qty]);
        return (int) $this->pdo->lastInsertId();
    }
    public function totalUnits(): int {
        return (int) ($this->pdo->query('SELECT COALESCE(SUM(qty),0) FROM orders')->fetchColumn());
    }
}

final class InMemoryOrderRepository implements OrderRepository {
    private array $orders = [];
    private int $next = 1;
    public function place(string $sku, int $qty): int {
        $id = $this->next++;
        $this->orders[] = ['sku' => $sku, 'qty' => $qty];
        return $id;
    }
    public function totalUnits(): int {
        return array_sum(array_column($this->orders, 'qty'));
    }
}

final class Checkout {
    public function __construct(private OrderRepository $repo) {}
    public function buy(array $cart): int {
        foreach ($cart as [$sku, $qty]) {
            $this->repo->place($sku, $qty);
        }
        return $this->repo->totalUnits();
    }
}

$cart = [['WIDGET', 2], ['GADGET', 3]];

$pdo = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$prod = new Checkout(new PdoOrderRepository($pdo));
echo 'pdo total: ', $prod->buy($cart), "\n";

$test = new Checkout(new InMemoryOrderRepository());
echo 'fake total: ', $test->buy($cart), "\n";

Output:

pdo total: 5
fake total: 5

The Checkout service takes an OrderRepository and never mentions PDO or SQL. Wired with PdoOrderRepository it persists orders to the database and sums them with COALESCE(SUM(qty),0); wired with InMemoryOrderRepository it stores them in an array and sums with array_sum. Both report a total of 5 units for the same cart, proving the service is genuinely decoupled from storage: the test path needs no database, runs instantly, and exercises the exact same buy logic that production uses.

The design flaw is that this repository has no unit-of-work boundary. buy places each cart line as its own place call, and in the PDO implementation each is an independent auto-committed insert. If the second line fails -- a constraint violation, a dropped connection -- the first line is already committed, leaving a half-placed order in the database. The in-memory fake cannot even exhibit this failure, so a passing test suite gives false confidence that the production path is atomic when it is not. A robust design would let the repository expose a transactional boundary, or accept the whole cart in one placeAll method that wraps its inserts in a transaction, so partial failure rolls back. As written, the pattern cleanly hides storage but silently abandons atomicity, and the fake hides that gap rather than revealing it -- a reminder that a test double must model the failure modes that matter, not just the happy path.


Common Mistakes

  1. Leaking storage details through the interface. Returning raw result arrays with column names, or a method only one database could serve, couples callers to the store. Return entities and keep methods intent-named.
  1. Letting the repository open its own connection. A repository that constructs its own PDO cannot be tested or reconfigured. Inject the connection so wiring stays in one place.
  1. Naming methods after SQL. A method called selectWhereEmailEquals exposes the mechanism. Name it findByEmail so the interface reads as business intent.
  1. Putting business logic in the repository. A repository fetches and stores; it should not calculate discounts or enforce workflow. Keep domain rules in services so the repository stays a thin data boundary.
  1. Skipping the interface entirely. A concrete-only repository still hides SQL, but you lose the swap-for-tests benefit. Define the interface so a fake can stand in.
  1. Making the fake diverge from the real one. An in-memory fake that behaves differently from the database gives false test confidence. Model the behaviours that matter, including relevant failure modes.
  1. Returning false for "not found". Mixing false with real data is error-prone. Return null or throw a dedicated not-found exception so callers handle absence clearly.
  1. Ignoring transactions across multiple writes. Placing several rows through separate calls loses atomicity. Provide a transactional method or boundary when a set of writes must succeed together.
  1. Building a giant repository. One class with fifty methods becomes unmanageable. Keep a repository focused on one aggregate, splitting when responsibilities diverge.

Best Practices

  • Define a repository interface in business terms, and implement it with a database-backed class that receives its connection by injection.
  • Name methods for what the application wants -- findByEmail, allActive, save -- never for the SQL that fulfils them.
  • Map rows to typed entity objects in one private method, so column names never escape the repository.
  • Return null or throw a not-found exception for absent records, keeping the "missing" signal distinct from real data.
  • Provide an in-memory fake implementing the same interface, and depend on the interface everywhere so tests need no database.
  • Keep domain logic in services and the repository thin, so each has a single clear responsibility.
  • Expose a transactional boundary or an all-in-one method when several writes must be atomic, so partial failure rolls back.
  • Keep each repository focused on one aggregate root, splitting rather than growing a single class without limit.

Practice Exercises

  1. Define a NoteRepository interface with save, find, and all, and implement it with a PDO-backed class. Save two notes and print them back through all.
  1. Write an InMemoryNoteRepository implementing the same interface with arrays, and a summary(NoteRepository $r): int function that returns the count, proving it works against both implementations.
  1. Add a Note entity class and a private map method so the repository returns Note objects instead of arrays, confirming that no caller references a column name.
  1. Give the repository a saveMany(array $notes): void method that wraps its inserts in a transaction, and demonstrate that a batch containing one invalid note rolls back so none are saved.