Skip to content
BENIBIX Learn

Repository Pattern

Development🏗️ ArchitectureDesign Patterns

Also known as Repository Design Pattern, Repository Layer

One class that hides how a kind of data is read and saved.

Think of it like

It is like a library desk. You ask for a book, and the librarian knows which shelf it is on.

Example

Jack's app asks the user repository to find a user by email. In tests, a fake one gives back users from a list. No database is needed.

Why it matters

Database code stays in one place, so a change of table or database touches little else. Tests run fast without a real database.

Definition

The repository pattern puts all the code that reads and saves one kind of data behind one class. Your app asks it for things, like find a user by email or save this order. Only the repository knows the database tables and queries. The rest of the code works with plain objects. In tests, you can swap the real repository for a fake one.

Example code

python
class UserRepository:
    def find_by_email(self, email):
        row = self.db.query_one("SELECT * FROM users WHERE email = %s", email)
        return User(**row) if row else None
Only the repository knows the SQL. The app gets a User object back.
Bottom right: the app asks the repository. Only that one talks to the database.

Common mistake

Adding a repository on top of an ORM that already does that job. Two layers for one task add code but no value.

Key takeaways

  1. 1
    One kind of data. One repository each.
  2. 2
    Hides the database. Plain objects come out.
  3. 3
    Easy to fake. Tests need no database.