Recall & Review
beginner
What is Dependency Injection in simple terms?
Dependency Injection means giving an object what it needs instead of making it create those things itself. It helps keep code clean and easy to change.
Click to reveal answer
beginner
Why is Dependency Injection useful?
It makes code easier to test, change, and reuse because parts don’t depend tightly on each other. You can swap parts without changing the whole system.
Click to reveal answer
intermediate
In PHP, what is a common way to implement Dependency Injection?
You pass the needed objects as parameters to a class constructor or method instead of creating them inside the class.Click to reveal answer
intermediate
What is the difference between Dependency Injection and Service Locator?
Dependency Injection gives dependencies directly to a class, while Service Locator asks a central place to get dependencies. DI is clearer and easier to test.
Click to reveal answer
beginner
Show a simple PHP example of Dependency Injection using constructor injection.
class Logger {
public function log($msg) {
echo $msg . "\n";
}
}
class User {
private $logger;
public function __construct(Logger $logger) {
$this->logger = $logger;
}
public function create() {
$this->logger->log('User created');
}
}
$logger = new Logger();
$user = new User($logger);
$user->create();Click to reveal answer
What does Dependency Injection help to achieve in code?
✗ Incorrect
Dependency Injection helps make components less dependent on each other, which is called loose coupling.
Which of these is a common way to inject dependencies in PHP?
✗ Incorrect
Passing dependencies through the constructor is a common and clean way to do Dependency Injection in PHP.
What is NOT a benefit of Dependency Injection?
✗ Incorrect
Dependency Injection reduces coupling, it does not make it tighter.
In Dependency Injection, who is responsible for creating the dependencies?
✗ Incorrect
Dependencies are created outside and passed in, often by a container or the code that uses the class.
Which pattern is considered clearer and easier to test?
✗ Incorrect
Dependency Injection is clearer and easier to test compared to Service Locator.
Explain Dependency Injection and why it is helpful in PHP programming.
Think about how objects get what they need without creating it themselves.
You got /3 concepts.
Describe how you would implement Dependency Injection in a PHP class with an example.
Focus on how dependencies are passed in and used inside the class.
You got /3 concepts.