What is the Repository pattern in PHP?
Why Interviewers Ask This
Senior PHP engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
The Repository pattern abstracts the data access layer, providing a collection-like interface for accessing domain objects. Business logic interacts with a repository interface, not directly with the database or ORM. Example: interface UserRepository { public function findById(int $id): User; public function findByEmail(string $email): ?User; public function save(User $user): void; }. Implement for Eloquent, Doctrine, or a plain array (for testing). Benefits: testability (inject a mock repository in unit tests), database independence (swap Eloquent for Doctrine without changing business logic), and separation of concerns (query logic lives in one place). In Laravel, repositories are often used as wrappers around Eloquent models to avoid coupling domain logic to the ORM.
Pro Tip
This topic has PHP-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.