What is the concept of Dependency Injection in PHP and how can it be applied to improve code structure?
Dependency Injection is a design pattern in which the dependencies of a class are injected from the outside rather than created within the class itself. This helps improve code structure by promoting loose coupling, making classes easier to test, reuse, and maintain.
// Example of Dependency Injection in PHP
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
public function query($sql) {
return $this->connection->query($sql);
}
}
class UserRepository {
private $database;
public function __construct(Database $database) {
$this->database = $database;
}
public function getUsers() {
$result = $this->database->query("SELECT * FROM users");
return $result->fetchAll();
}
}
// Usage
$database = new Database('localhost', 'root', 'password', 'mydatabase');
$userRepository = new UserRepository($database);
$users = $userRepository->getUsers();