Repository pattern with PDO
Keep SQL in one class. The rest of the app asks for users and never writes queries.
PHP · Repository pattern with PDOAdvanced
final class UserRepository
{
public function __construct(private PDO $pdo) {}
public function find(int $id): ?array
{
$st = $this->pdo->prepare('SELECT * FROM users WHERE id = ?');
$st->execute([$id]);
return $st->fetch() ?: null;
}
public function findByEmail(string $email): ?array
{
$st = $this->pdo->prepare('SELECT * FROM users WHERE email = ?');
$st->execute([$email]);
return $st->fetch() ?: null;
}
public function save(array $u): int
{
if (!empty($u['id'])) {
$st = $this->pdo->prepare('UPDATE users SET name = ?, email = ? WHERE id = ?');
$st->execute([$u['name'], $u['email'], $u['id']]);
return (int)$u['id'];
}
$st = $this->pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
$st->execute([$u['name'], $u['email']]);
return (int)$this->pdo->lastInsertId();
}
}
$users = new UserRepository($pdo);
$id = $users->save(['name' => 'Hina', 'email' => 'hina@example.com']);
$users->save(['id' => $id, 'name' => 'Hina Q', 'email' => 'hina@example.com']);
$u = $users->find($id);repositorypdodesign