Is it advisable to separate database queries into a separate class when working with PHP objects, or is it acceptable to include them directly in other classes?

It is advisable to separate database queries into a separate class when working with PHP objects to follow the principles of separation of concerns and maintainability. This approach helps in keeping the database-related logic isolated and reusable, making the code easier to understand and maintain. By creating a separate class for database queries, you can also easily switch between different database systems or make changes to the queries without affecting other parts of the code.

<?php

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
    }

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

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

class User {
    private $db;

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

    public function getUserById($id) {
        $result = $this->db->query("SELECT * FROM users WHERE id = $id");
        return $result->fetch_assoc();
    }
}

$db = new Database('localhost', 'username', 'password', 'database');
$user = new User($db);

$userData = $user->getUserById(1);
print_r($userData);

$db->close();

?>