How can dependency injection or inversion of control be implemented in PHP to manage class relationships more effectively?
Dependency injection or inversion of control can be implemented in PHP by passing dependencies into a class rather than having the class create its own dependencies. This allows for better decoupling of classes and easier testing and maintenance. One way to achieve this is by using constructor injection, where dependencies are passed into a class through its constructor.
// Example of implementing dependency injection in PHP using constructor injection
class Database {
public function __construct($host, $username, $password) {
// Database connection logic
}
}
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
// Other methods using $this->db
}
// Usage
$db = new Database('localhost', 'root', 'password');
$userRepository = new UserRepository($db);