What are the advantages and disadvantages of using a repository pattern for handling database queries in PHP?
When handling database queries in PHP, using a repository pattern can help separate database logic from business logic, making the code more maintainable and testable. It also allows for easier switching between different data sources without affecting the rest of the codebase. However, implementing a repository pattern can introduce additional complexity and overhead, especially for smaller projects where the benefits may not be as apparent.
// Example of implementing a repository pattern for handling database queries in PHP
interface UserRepositoryInterface {
public function findById(int $id): array;
public function findAll(): array;
public function save(array $data): bool;
}
class UserRepository implements UserRepositoryInterface {
private $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function findById(int $id): array {
$stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => $id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function findAll(): array {
$stmt = $this->db->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function save(array $data): bool {
$stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
return $stmt->execute(['name' => $data['name'], 'email' => $data['email']]);
}
}
// Example usage
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$userRepository = new UserRepository($db);
$user = $userRepository->findById(1);
$users = $userRepository->findAll();
$newUser = ['name' => 'John Doe', 'email' => 'john@example.com'];
$result = $userRepository->save($newUser);
Related Questions
- How can PHP beginners ensure their code follows best practices to prevent errors in browsers?
- How can PHP beginners ensure that their scripts are properly integrated into their website's structure to avoid displaying blank pages?
- How can one display the corresponding images for each vehicle in a PHP script similar to websites like mobile.de?