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();
Related Questions
- In what scenarios would a seemingly syntactically incorrect PHP code snippet actually work, and how can developers ensure clarity and accuracy in their coding practices?
- What are some best practices for implementing a CAPTCHA system in PHP to prevent spam submissions in contact forms?
- Was könnte die Ursache für die Fehlermeldung bei der MySQL-Abfrage sein?