How can Dependency Injection be utilized to improve the management of database connections in PHP classes?
When managing database connections in PHP classes, using Dependency Injection can improve flexibility and testability by allowing the database connection to be injected into the class rather than hardcoding it. This means the class can easily switch between different database connections or use mock connections for testing purposes.
<?php
class Database
{
private $connection;
public function __construct(PDO $connection)
{
$this->connection = $connection;
}
public function query($sql)
{
return $this->connection->query($sql);
}
}
// Usage
$pdo = new PDO("mysql:host=localhost;dbname=test", "username", "password");
$database = new Database($pdo);
$result = $database->query("SELECT * FROM users");
foreach ($result as $row) {
echo $row['username'] . "\n";
}