Back to results for “Unit Testing with PHPUnit”
PHP › Design Patterns in PHP

How does the Repository pattern abstract data access logic away from an application's business logic, and what benefits does this separation provide?

Advanced

Answer

The Repository pattern introduces a dedicated layer responsible for retrieving and persisting data, exposing a clean, collection like interface to the rest of the application while hiding the actual details of how that data is stored, whether in a relational database, a NoSQL store, or even an external API, which lets business logic remain completely unaware of and unaffected by the specific underlying data storage technology, and makes it significantly easier to substitute a fake in memory repository during testing.
interface UserRepository {
    public function find(int $id): ?User;
    public function save(User $user): void;
}
class EloquentUserRepository implements UserRepository {
    public function find(int $id): ?User { return User::find($id); }
}
Real-world example A team testing their order processing logic substitutes a simple in memory fake repository implementing the same UserRepository interface, allowing their tests to run quickly without touching an actual database while still exercising the real business logic.

Common follow-ups: How does the Repository pattern relate to and differ from using an ORM directly?;What are the tradeoffs of adding a Repository layer on top of an ORM like Eloquent that already provides similar abstraction?