How can dependencies be managed effectively when instantiating objects within a class in PHP, particularly when working with database connections like mysqli?
When instantiating objects within a class in PHP, particularly when working with database connections like mysqli, it is important to manage dependencies effectively to ensure clean and maintainable code. One way to achieve this is by using dependency injection, where the dependencies are passed into the class constructor or methods rather than being created inside the class itself. This allows for better separation of concerns and makes it easier to test and reuse the code.
<?php
class Database {
private $connection;
public function __construct(mysqli $connection) {
$this->connection = $connection;
}
public function query($sql) {
return $this->connection->query($sql);
}
}
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
$database = new Database($mysqli);
$result = $database->query('SELECT * FROM table');
?>
Related Questions
- What are the potential pitfalls of storing multiple values in a single database cell in PHP?
- Are there any best practices to follow when saving text from a textarea into files in PHP?
- What best practices can be followed to improve the handling of date and time data in PHP applications, considering the challenges faced in the forum thread discussion?