Should data retrieval and storage from a database be handled within a PHP repository or a separate handler?

When working with databases in PHP, it is generally recommended to separate data retrieval and storage logic into a separate handler class. This approach follows the principles of separation of concerns and helps to keep the codebase organized and maintainable. By creating a separate handler for database operations, you can encapsulate the database-related logic, make it reusable, and easily switch between different data storage implementations if needed.

<?php
// DatabaseHandler.php

class DatabaseHandler {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

    public function getData($query) {
        $result = $this->connection->query($query);
        $data = [];
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
        return $data;
    }

    public function insertData($query) {
        return $this->connection->query($query);
    }

    public function closeConnection() {
        $this->connection->close();
    }
}
?>