How can Dependency Injection be implemented in PHP to create loose bindings between classes and improve code maintainability?
Dependency Injection in PHP can be implemented by passing dependencies into a class's constructor or methods, rather than creating them within the class itself. This helps create loose bindings between classes, making it easier to swap out dependencies and improve code maintainability.
// Example of Dependency Injection in PHP
class Database {
public function query($sql) {
// Database query logic here
}
}
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getUsers() {
return $this->db->query("SELECT * FROM users");
}
}
// Usage
$db = new Database();
$userRepository = new UserRepository($db);
$users = $userRepository->getUsers();