What is Dependency Injection and why is it recommended over global variables or constructor-based instantiation in PHP?
Dependency Injection is a design pattern in which the dependencies of a class are provided from the outside rather than created internally. This allows for better flexibility, testability, and maintainability of the code. It is recommended over global variables or constructor-based instantiation in PHP because it promotes loose coupling between classes and makes it easier to swap out dependencies or mock them for testing purposes.
class Database {
private $connection;
public function __construct(PDO $connection) {
$this->connection = $connection;
}
public function query($sql) {
// execute query using $this->connection
}
}
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
$database->query("SELECT * FROM table");
Related Questions
- What are the potential pitfalls of using LIMIT in a MySQL query to retrieve the latest entries?
- What role does SSL certification play in the interaction between a website and social media platforms like Facebook?
- How can the use of static methods in PHP classes affect the flexibility and maintainability of the code?