0
0
PHPprogramming~30 mins

Dependency injection concept in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Dependency Injection in PHP
📖 Scenario: You are building a simple PHP application that sends notifications. To keep your code clean and easy to change, you want to use dependency injection. This means you will give the notification sender to the notifier instead of making the notifier create it itself.
🎯 Goal: Learn how to use dependency injection by creating a notifier class that receives a sender object. You will create the sender, inject it into the notifier, and then send a notification message.
📋 What You'll Learn
Create a class called EmailSender with a method send that prints a message.
Create a class called Notifier that accepts a sender object in its constructor and stores it.
Add a method notify in Notifier that calls the sender's send method with a message.
Create an instance of EmailSender and inject it into Notifier.
Call the notify method to send a notification.
💡 Why This Matters
🌍 Real World
Dependency injection is used in many PHP frameworks to manage how objects get their dependencies, making code easier to test and maintain.
💼 Career
Understanding dependency injection is important for working with modern PHP frameworks like Laravel or Symfony, which use this pattern extensively.
Progress0 / 4 steps
1
Create the EmailSender class
Create a class called EmailSender with a public method send that takes a parameter $message and prints "Sending email: " followed by the message.
PHP
Need a hint?

Define a class with class EmailSender {}. Inside, add a public function send that uses echo to print the message.

2
Create the Notifier class with dependency injection
Create a class called Notifier with a private property $sender. Add a constructor that takes a parameter $sender and assigns it to the property $sender.
PHP
Need a hint?

Define a class Notifier with a private property $sender. The constructor should accept $sender and assign it to $this->sender.

3
Add notify method to call sender's send
In the Notifier class, add a public method notify that takes a parameter $message and calls $this->sender->send($message).
PHP
Need a hint?

Add a method notify that uses $this->sender->send($message) to send the message.

4
Create instances and send notification
Create an instance of EmailSender called $emailSender. Create an instance of Notifier called $notifier by injecting $emailSender. Call $notifier->notify("Hello World") to send the notification.
PHP
Need a hint?

Create the sender and inject it into the notifier. Then call notify with the message.