What are the potential pitfalls of not using Dependency Injection when defining database connections in PHP classes?
Not using Dependency Injection when defining database connections in PHP classes can lead to tightly coupled code, making it difficult to test and maintain. By using Dependency Injection, we can easily swap out different database connections for testing or changing databases without modifying the class itself.
class DatabaseConnection {
private $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function query($sql) {
return $this->db->query($sql);
}
}
// Usage
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$connection = new DatabaseConnection($db);
$result = $connection->query('SELECT * FROM users');
Keywords
Related Questions
- In terms of scalability and performance, what are some best practices for handling tab navigation in a PHP project with multiple users and classes?
- What potential issues can arise when not properly ordering entries in a PHP guestbook by date?
- How can PHP developers avoid errors related to variable initialization in nested loops?