What are the best practices for utilizing Dependency Injection in PHP projects?
When working on PHP projects, utilizing Dependency Injection is a best practice to improve code maintainability and testability. By injecting dependencies into classes rather than creating them internally, it allows for easier swapping of dependencies and reduces coupling between classes. Example PHP code snippet implementing Dependency Injection:
class Database {
private $connection;
public function __construct(PDO $connection) {
$this->connection = $connection;
}
public function query($sql) {
return $this->connection->query($sql);
}
}
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$database = new Database($pdo);
$result = $database->query('SELECT * FROM users');