What are the potential pitfalls of mixing logic and persistence layers in PHP code?

Mixing logic and persistence layers in PHP code can lead to code that is difficult to maintain, understand, and test. It can also make it challenging to switch out the persistence layer or make changes to the logic without affecting the other. To solve this issue, it is recommended to separate the logic and persistence layers by using a design pattern like the Repository pattern.

// Example of separating logic and persistence layers using the Repository pattern

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->bindParam(':id', $id);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Other methods for interacting with the users table
}

// Example of using the UserRepository
$db = new PDO("mysql:host=localhost;dbname=test", "username", "password");
$userRepository = new UserRepository($db);

$user = $userRepository->getUserById(1);