What are the best practices for handling database access within PHP classes?
When handling database access within PHP classes, it is best practice to encapsulate database interactions within the class itself, rather than directly accessing the database from outside the class. This helps to maintain separation of concerns and makes the class more reusable and testable. One common approach is to use dependency injection to pass a database connection object to the class constructor, allowing for easier testing and flexibility in changing the database connection in the future.
class DatabaseHandler {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function fetchData() {
$query = "SELECT * FROM table";
$result = $this->db->query($query);
// Process the result
return $result;
}
}
// Usage
$db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$handler = new DatabaseHandler($db);
$data = $handler->fetchData();