0
0
PHPprogramming~10 mins

Dependency injection concept in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to inject the Logger dependency into the UserService constructor.

PHP
<?php
class UserService {
    private $logger;
    public function __construct([1] $logger) {
        $this->logger = $logger;
    }
}
Drag options to blanks, or click blank then click option'
ALogger
BUserService
CDatabase
DConfig
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong class name in the constructor parameter.
Not specifying a type for the constructor parameter.
2fill in blank
medium

Complete the code to create a new UserService instance with a Logger injected.

PHP
<?php
$logger = new [1]();
$userService = new UserService($logger);
Drag options to blanks, or click blank then click option'
AUserService
BLogger
CDatabase
DConfig
Attempts:
3 left
💡 Hint
Common Mistakes
Creating the wrong class instance.
Not creating an instance before injecting.
3fill in blank
hard

Fix the error in the constructor to properly assign the injected dependency.

PHP
<?php
class UserService {
    private $logger;
    public function __construct(Logger $logger) {
        $this->[1] = $logger;
    }
}
Drag options to blanks, or click blank then click option'
Alog
BlogService
Clogger
DLogger
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different property name than declared.
Using uppercase or incorrect casing.
4fill in blank
hard

Fill both blanks to complete the setter method for dependency injection.

PHP
<?php
class UserService {
    private $logger;
    public function [1](Logger $logger) {
        $this->[2] = $logger;
    }
}
Drag options to blanks, or click blank then click option'
AsetLogger
BgetLogger
Clogger
Dlog
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'get' instead of 'set' for the method name.
Assigning to a wrong property name.
5fill in blank
hard

Fill all three blanks to complete the code that uses dependency injection with interface and implementation.

PHP
<?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");
    }
}
Drag options to blanks, or click blank then click option'
ALoggerInterface
Clog
Dwrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using the implementation class name instead of interface in constructor.
Calling a method name that does not exist.