Is it considered good practice to include database query commands directly within a class or its functions in PHP?

It is generally not considered good practice to include database query commands directly within a class or its functions in PHP as it violates the principles of separation of concerns and can make the code harder to maintain and test. Instead, it is recommended to use a separate data access layer, such as a repository pattern, to handle database interactions.

// Example of using a repository pattern to handle database interactions

class UserRepository {
    private $db;

    public function __construct($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();
    }

    public function updateUser($id, $name) {
        $stmt = $this->db->prepare("UPDATE users SET name = :name WHERE id = :id");
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':name', $name);
        $stmt->execute();
    }
}

// Example of how to use the UserRepository class
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$userRepository = new UserRepository($db);

$user = $userRepository->getUserById(1);
$userRepository->updateUser(1, 'John Doe');