Complete the code to inject the Logger dependency into the UserService constructor.
<?php class UserService { private $logger; public function __construct([1] $logger) { $this->logger = $logger; } }
The constructor requires an instance of the Logger class to be injected. This is dependency injection.
Complete the code to create a new UserService instance with a Logger injected.
<?php
$logger = new [1]();
$userService = new UserService($logger);You must create a Logger object to inject it into UserService.
Fix the error in the constructor to properly assign the injected dependency.
<?php class UserService { private $logger; public function __construct(Logger $logger) { $this->[1] = $logger; } }
The property name is $logger, so assign to $this->logger.
Fill both blanks to complete the setter method for dependency injection.
<?php class UserService { private $logger; public function [1](Logger $logger) { $this->[2] = $logger; } }
The setter method is named setLogger and assigns to the property $logger.
Fill all three blanks to complete the code that uses dependency injection with interface and implementation.
<?php
interface LoggerInterface {
public function log(string $message);
}
class FileLogger implements [1] {
public function log(string $message) {
// write to file
}
}
class UserService {
private $logger;
public function __construct([2] $logger) {
$this->logger = $logger;
}
public function doAction() {
$this->logger->[3]("Action done");
}
}The class FileLogger implements LoggerInterface. The constructor type hints LoggerInterface. The method called is log.