What are the potential pitfalls of using DB classes in PHP, and what alternative approach, like Dependency Injection, can be more beneficial?
Using DB classes in PHP can lead to tightly coupled code, making it difficult to test and maintain. Dependency Injection, on the other hand, allows for more flexibility and easier testing by injecting dependencies into a class rather than hardcoding them.
// DB Class Example
class DB {
public function query($sql) {
// Database connection logic
}
}
// Using DB class directly
$db = new DB();
$db->query("SELECT * FROM users");
// Using Dependency Injection
class User {
private $db;
public function __construct(DB $db) {
$this->db = $db;
}
public function getUsers() {
return $this->db->query("SELECT * FROM users");
}
}
// Injecting DB class into User class
$db = new DB();
$user = new User($db);
$user->getUsers();