Proper Repository Pattern Design in PHP?
Transitioning from direct database coupling to a repository pattern driven by an IoC container is a significant architectural shift. However, moving that query logic into the repository layer often introduces new complexity regarding interface contracts and method proliferation. When designing repositories for relational databases, you face three specific challenges: selecting only necessary columns, managing a growing list of complex queries without bloating your controller, and maintaining a stable interface as requirements evolve.
Selective Field Retrieval
The first issue arises from the temptation to implement findAll(), findById(), or findByName() as generic wrappers that execute SELECT *. In high-throughput applications, fetching unnecessary columns increases network payload size and memory overhead. A robust repository design should not enforce a rigid "select all" contract for every find method.
Instead, your interface methods should accept an array of column names to fetch. This shifts the responsibility of field selection from the database layer to the application logic, but keeps the query structure centralized. In PHP, using a fluent builder pattern or passing explicit column arrays is common. For instance, rather than defining findByName($name) which implies fetching all columns, you might define findByColumn(string $column, string $value): array where the caller specifies exactly what they need:
public interface UserRepositoryInterface {
/**
* Retrieve users with only specific fields to reduce payload size.
*/
public function findByColumn(string $column, string $value, array $columns = ['id', 'name']): array;
}
class DbUserRepository implements UserRepositoryInterface {
protected $db;
public function __construct($db) {
$this->db = $db;
}
public function findByColumn(string $column, string $value, array $columns = []) {
// Construct a dynamic query based on the requested columns
return $this->db->select($columns)
->from('users')
->where($column, '=', $value)
->execute()
->fetchAll();
}
}
This approach allows your controller to request only ['name', 'email'] when displaying a list, while the repository handles the SQL generation dynamically. It prevents the "select all" anti-pattern without forcing every method signature to change.
Managing Query Complexity
The second challenge is the explosion of methods. As you add filters like findAllInCountry or complex ordering logic, your interface grows unwieldy. Refactoring a controller from verbose chaining (User::select()->byCountry()) into a single method call with a cryptic string name (e.g., get_first_name_last_name_email_username_status_by_country_order_by_name('Canada')) is indeed a step backward in readability.
The solution lies in accepting that the repository interface will evolve, but doing so strategically. You do not need to implement every possible query combination as a distinct method immediately. If you anticipate complex filtering logic, consider using a specification pattern or a dedicated query builder within the repository implementation.
However, if you strictly adhere to an interface contract, the best practice is to group related queries. Instead of findAllInCountry, define a method that accepts a filter array or a closure:
public function findAll(array $conditions = []): array {
// Build query based on conditions passed in
return $this->db->select('*')->from('users')->where($conditions)->execute()->fetchAll();
}
This keeps the interface stable while allowing the implementation to handle complex logic internally. Alternatively, move the complex chaining logic into the repository methods themselves, returning collections that match your domain objects exactly, rather than forcing the controller to know about specific SQL fragments.
Interface Stability and Evolution
The third issue is the fear of updating the interface. Developers often worry that adding a new method like findAllInCountry breaks existing implementations or forces everyone to update the contract. This is a valid concern regarding interface coupling.
The reality is that interfaces define a minimum contract, not a maximum ceiling. If your application relies on specific repository methods, those implementations must exist. However, you can mitigate this by separating "core" operations (CRUD) from "complex" operations. Core operations like save, remove, and generic find remain stable. Complex queries often belong in separate service classes or can be added to the interface only when they become a standard requirement for your domain model.
If you use an IoC container, you can also consider creating multiple repository interfaces for different domains (e.g., UserRepository vs. AdminUserRepository). This allows the Admin repo to have complex methods without affecting the core User repo used by public controllers. This architectural decision prevents the "tail wagging the dog" scenario where interface changes ripple through unrelated parts of your system.
Ultimately, the repository pattern is not about hiding database complexity behind a static list of methods; it is about encapsulating data access logic so that the rest of your application remains decoupled from SQL dialects and schema changes.