What are the best practices for handling database connections in OOP PHP classes?
When working with database connections in OOP PHP classes, it is best practice to create a separate database class that handles the connection and query execution. This helps to keep your code organized and maintainable. Additionally, using dependency injection to pass the database connection object to your classes can make it easier to test and reuse your code.
<?php
class Database {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'mydatabase';
private $conn;
public function __construct() {
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
public function getConnection() {
return $this->conn;
}
}
class MyClass {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function fetchData() {
$conn = $this->db->getConnection();
$stmt = $conn->query("SELECT * FROM my_table");
return $stmt->fetchAll();
}
}
// Usage
$db = new Database();
$obj = new MyClass($db);
$data = $obj->fetchData();
print_r($data);
?>