Understanding Dependency Injection

Today we are going to learn about what is dependency injection in PHP. I was reading about new PHP updates eventually, I saw that they mentioned dependency injection, so I thought I should write on this topic.

Well, it’s a cool topic whenever I go through something new I usually write new topics. Sooner I’l be going through AI things with PHP/ Laravel. It’s important to visit the website once in a week to get updates about new things.

So, we will discuss Dependency Injection: Whenever we use any other class in an already written class. Let me give an example, For example, we have a class called `User` and we wanna log some messages.

The first thing that we will think about to create a logger Class and then create an object and pass the message in Construct Method.

And the second thing is Dependency Injection.

What is Dependency Injections

The Dependency Injection (DI) is a design pattern commonly used in object-oriented programming languages, including PHP. It is a technique that allows objects to be created and dependencies to be provided externally, rather than being created internally within the object itself.

The purpose of using Dependency Injection is to make code more modular, flexible, and easy to maintain, and test. Well, it’s a very cool thing from my point of view.

You can inject any class in any method, But there we have some Types Of Dependency Injections.

Types Of Dependency Injections

Dependency Injection is a powerful design pattern in PHP that promotes code modularity, flexibility, and testability.

Let’s explore three types of Dependency Injections.

Constructor Injection

Constructor Injection involves passing dependencies to a class through its constructor. The class declares parameters in its constructor for the required dependencies, which are then passed when creating an instance of the class. This type of injection ensures that the dependencies are available immediately upon object creation.

class Logger {
    public function log($message) {
        echo "Logging message: $message\n";
    }
}

class User {
    private $logger;

    public function __construct(Logger $logger) {
        $this->logger = $logger;
    }

    public function register() {
        // Perform user registration logic

        // Log a message
        $this->logger->log('User registered successfully.');
    }
}

// Create an instance of the Logger
$logger = new Logger();

// Create an instance of the User and inject the Logger
$user = new User($logger);

// Call the register method, which will log a message
$user->register();

See, how we injected the Logger Class in the above code to take logs.

Setter Injection

Setter Injection involves injecting dependencies through setter methods of a class. The class exposes setter methods for each dependency, allowing the dependencies to be set after creating an instance of the class. This type of injection provides more flexibility in managing dependencies.

class User {
    private $logger;

    public function setLogger(Logger $logger) {
        $this->logger = $logger;
    }

    public function register() {
        // Perform user registration logic

        // Log a message
        $this->logger->log('User registered successfully.');
    }
}

// Create an instance of the User
$user = new User();

// Create an instance of the Logger
$logger = new Logger();

// Inject the Logger dependency into the User object
$user->setLogger($logger);

// Call the register method, which will log a message
$user->register();

So, the setter injection will set the external class after creating the object from the same class. ‘

It’s useful if you don’t want to auto-inject the class in construct. Well, you can do that by using any method. But specifically, setter makes sense.

Interface Injection

Interface Injection involves implementing an interface that defines the contract for a dependency. The dependency is then set by passing an object that implements the interface. This type of injection provides loose coupling and allows for runtime determination of dependencies.

interface PaymentProcessor {
    public function processPayment();
}

class PayPalProcessor implements PaymentProcessor {
    public function processPayment() {
        echo "Processing payment using PayPal.\n";
    }
}

class StripeProcessor implements PaymentProcessor {
    public function processPayment() {
        echo "Processing payment using Stripe.\n";
    }
}

class PaymentGateway {
    private $processor;

    public function setPaymentProcessor(PaymentProcessor $processor) {
        $this->processor = $processor;
    }

    public function processPayment() {
        $this->processor->processPayment();
    }
}

// Create an instance of the PaymentGateway
$gateway = new PaymentGateway();

// Create an instance of the PayPalProcessor
$paypalProcessor = new PayPalProcessor();

// Inject the PayPalProcessor dependency into the PaymentGateway object
$gateway->setPaymentProcessor($paypalProcessor);

// Process payment using the injected processor
$gateway->processPayment();

This is a bit different than the above two ways.

Let’s understand what this exactly is:

In this example, we define the PaymentProcessor interface and create two classes, PayPalProcessor and StripeProcessor, that implement this interface. The PaymentGateway class exposes a setPaymentProcessor method that accepts an object implementing the PaymentProcessor interface. The specific payment processor is injected into the PaymentGateway object, and the payment is processed using the injected processor.

Conclusion

Dependency injection is a powerful technique that promotes code reusability, testability, and maintainability. It allows for better decoupling between classes and facilitates easier changes and updates in the future.

As you delve deeper into PHP and Laravel, exploring topics related to AI, make sure to keep yourself updated by regularly visiting relevant websites and resources. Stay curious, keep learning, and always apply your skills in an ethical and responsible manner.

3 thoughts on “Understanding Dependency Injection”

Leave a Comment