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
}
Related Questions
- What are the best practices for handling character encoding in PHP projects?
- How can the issue of only displaying the source code of the .php file when clicking a link on the homepage be resolved?
- What are some potential solutions for downloading image packages from users to improve game performance in PHP?