How can Dependency Injection Containers be implemented in PHP to manage object dependencies more effectively?
Dependency Injection Containers can be implemented in PHP by creating a container class that manages the instantiation and injection of object dependencies. This allows for better decoupling of classes and makes it easier to manage dependencies throughout an application.
class Container {
private $dependencies = [];
public function set($key, $value) {
$this->dependencies[$key] = $value;
}
public function get($key) {
if (isset($this->dependencies[$key])) {
return $this->dependencies[$key];
}
return null;
}
}
// Example of setting and getting dependencies from the container
$container = new Container();
$container->set('db', new Database());
$db = $container->get('db');