How can Dependency Injection be implemented in PHP without relying on a large framework?
Dependency Injection is a design pattern that allows for decoupling of components by passing dependencies into a class rather than creating them within the class itself. In PHP, Dependency Injection can be implemented without relying on a large framework by manually injecting dependencies into the constructor or setter methods of a class.
class Logger {
private $storage;
public function __construct(Storage $storage) {
$this->storage = $storage;
}
public function log($message) {
$this->storage->save($message);
}
}
class Storage {
public function save($data) {
// Save data to storage
}
}
$storage = new Storage();
$logger = new Logger($storage);
$logger->log("Hello, world!");