What are the benefits of using Dependency Injection over Singleton or Registry Pattern for managing database connections in PHP?

When managing database connections in PHP, using Dependency Injection over Singleton or Registry Pattern offers several benefits. Dependency Injection promotes better code organization and testability by explicitly defining and injecting dependencies into classes. This approach also allows for easier swapping of different database connection implementations and reduces tight coupling between classes.

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=test', 'username', 'password');
$database = new Database($pdo);

$result = $database->query('SELECT * FROM users');
foreach ($result as $row) {
    // process each row
}