Understanding Dependency Injection In PHP

Oluwasegun Emmanuel Adeyemi
Cuesoft
Published in
2 min readDec 24, 2022

Dependency injection is a design pattern that allows a class to receive its dependencies from external sources rather than creating them itself. This allows for better separation of concerns, easier testing, and more flexibility in the application.

In PHP, dependency injection is typically implemented using either constructor injection or setter injection.

Constructor injection

Constructor injection is a form of dependency injection where the dependencies are passed to the class through the constructor.

For example, consider the following class EmailService that sends emails:

class EmailService {
private $mailer;

public function __construct(Mailer $mailer) {
$this->mailer = $mailer;
}

public function sendEmail($to, $subject, $body) {
$this->mailer->send($to, $subject, $body);
}
}

The EmailService class has a dependency on a Mailer object, which is injected through the constructor. This allows the EmailService to use any implementation of the Mailer interface, making it more flexible and easier to test.

To use the EmailService, you can simply create a new instance and pass in the required dependencies:

$mailer = new SMTPMailer();
$emailService = new EmailService($mailer);
$emailService->sendEmail('john@example.com', 'Hello', 'Hello, how are you?');

Setter injection

Setter injection is a form of dependency injection where the dependencies are set through setter methods.

For example, consider the following class PaymentProcessor that processes payments:

class PaymentProcessor {
private $gateway;

public function setGateway(PaymentGateway $gateway) {
$this->gateway = $gateway;
}

public function processPayment($amount) {
$this->gateway->charge($amount);
}
}

The PaymentProcessor class has a dependency on a PaymentGateway object, which is injected through the setGateway setter method. This allows the PaymentProcessor to use any implementation of the PaymentGateway interface, making it more flexible and easier to test.

To use the PaymentProcessor, you can create a new instance and set the required dependencies:

$gateway = new StripePaymentGateway();
$paymentProcessor = new PaymentProcessor();
$paymentProcessor->setGateway($gateway);
$paymentProcessor->processPayment(100);

There are also some PHP libraries that can help with dependency injection, such as Pimple, PHP-DI, and Zend Framework’s Dependency Injection component. These libraries provide additional features such as automatic injection, lazy loading, and more.

I hope this helps to give you an understanding of dependency injection in PHP. Let me know if you have any questions.

--

--