What role does a repository play in separating data access logic from models in PHP applications?

Separating data access logic from models in PHP applications is important for maintaining clean and organized code. By using a repository pattern, we can abstract the database interactions into separate classes, making it easier to test and swap out different data sources without affecting the core application logic.

// UserRepository.php
class UserRepository {
    private $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    public function getUserById($id) {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->execute(['id' => $id]);

        return $stmt->fetch();
    }

    // Add more methods for CRUD operations
}