How can Dependency Injection be configured for practical use in PHP applications?
Dependency Injection in PHP applications can be configured by creating a container that manages the dependencies and injects them into classes when needed. This helps in decoupling classes and making them more testable and maintainable.
// Container class to manage dependencies
class Container {
private $dependencies = [];
public function __construct() {
$this->dependencies['db'] = new Database(); // Example dependency
}
public function getDependency($key) {
return $this->dependencies[$key];
}
}
// Example class using dependency injection
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getUsers() {
return $this->db->query('SELECT * FROM users');
}
}
// Usage
$container = new Container();
$userRepository = new UserRepository($container->getDependency('db'));
$users = $userRepository->getUsers();
Related Questions
- What are the best practices for managing and updating content in a database using PHP for a website with multiple pages?
- Is it advisable to use concatenation within loops in PHP to output data, or are there more efficient alternatives?
- When migrating PHP code to adhere to modern standards, what steps can be taken to update database interactions from deprecated functions like mysql_query to more secure alternatives?