How can Dependency Injection be used to add instances to a class in PHP?
Dependency Injection is a design pattern used to inject dependencies into a class instead of the class creating its dependencies internally. This promotes loose coupling and makes the code more testable and maintainable. In PHP, you can achieve Dependency Injection by passing instances of dependencies to a class through its constructor or setter methods.
// Example of using Dependency Injection in PHP
class Database {
public function query($sql) {
// Database query logic
return "Query executed: $sql";
}
}
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getUserById($id) {
$sql = "SELECT * FROM users WHERE id = $id";
return $this->db->query($sql);
}
}
// Usage
$db = new Database();
$userRepository = new UserRepository($db);
echo $userRepository->getUserById(1);
Related Questions
- What are some common challenges when trying to format and style MySQL tables displayed using PHP?
- What are the potential pitfalls of using if statements with assignment operators in PHP?
- What are the common pitfalls to avoid when working with serialized data in a PHP application, especially when it comes to sorting and querying the data?