🏗️Repository Pattern
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.
Definition
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 NoneCommon mistake
Key takeaways
- 1One kind of data. One repository each.
- 2Hides the database. Plain objects come out.
- 3Easy to fake. Tests need no database.