How can Dependency Injection and TypeHinting be utilized to improve the handling of class dependencies in PHP?
When dealing with class dependencies in PHP, Dependency Injection and TypeHinting can greatly improve code readability, maintainability, and testability. Dependency Injection allows for injecting dependencies into a class from the outside, making it easier to swap out implementations or mock dependencies for testing. TypeHinting ensures that the correct types of dependencies are passed to a class, reducing the chances of runtime errors.
// Using Dependency Injection and TypeHinting to handle class dependencies
class Database {
public function query(string $sql) {
// Database query logic
}
}
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getAllUsers() {
return $this->db->query('SELECT * FROM users');
}
}
// Usage
$database = new Database();
$userRepository = new UserRepository($database);
$users = $userRepository->getAllUsers();