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();
?>
Related Questions
- What are the common errors that can occur when checking for the existence of a directory using is_dir in PHP?
- How can the error "supplied argument is not a valid MySQL result resource" be resolved when fetching data in PHP?
- In what situations could using odbc_connect instead of PEAR or mssql_connect be a viable solution for connecting to a MSSQL database from PHP?