DEV Community

vimuth
vimuth

Posted on

PHP Interfaces and Their Usage with Dependency Injection

What is a PHP Interface?
An interface in PHP is a blueprint for classes. It defines a contract that any implementing class must adhere to, specifying methods that must be implemented but not providing the method bodies. Interfaces ensure a consistent structure across different classes and enable polymorphism by allowing multiple classes to be treated through a common interface.

Example:

1.Define an Interface:

interface PaymentGatewayInterface {
    public function charge($amount);
}
Enter fullscreen mode Exit fullscreen mode

This interface defines a charge method that any implementing class must provide.

2.Implement the Interface:

class StripePaymentGateway implements PaymentGatewayInterface {
    public function charge($amount) {
        // Implementation for Stripe
        return "Charged {$amount} using Stripe.";
    }
}

class PaypalPaymentGateway implements PaymentGatewayInterface {
    public function charge($amount) {
        // Implementation for PayPal
        return "Charged {$amount} using PayPal.";
    }
}
Enter fullscreen mode Exit fullscreen mode

Both StripePaymentGateway and PaypalPaymentGateway implement the PaymentGatewayInterface, providing their specific implementations of the charge method.

3.Using the Interface:

function processPayment(PaymentGatewayInterface $paymentGateway, $amount) {
    return $paymentGateway->charge($amount);
}

$stripe = new StripePaymentGateway();
$paypal = new PaypalPaymentGateway();

echo processPayment($stripe, 100); // Output: Charged 100 using Stripe.
echo processPayment($paypal, 200); // Output: Charged 200 using PayPal.

Enter fullscreen mode Exit fullscreen mode

The processPayment function accepts any object that implements PaymentGatewayInterface, allowing for flexible and interchangeable use of payment gateways.

Summary

PHP interfaces are crucial for defining consistent method signatures across different classes, enabling polymorphism, and enhancing code maintainability and flexibility. They play a vital role in modern PHP applications, particularly in scenarios involving dependency injection and service-oriented architectures.

And they are very useful for dependency injection. Instead of adding a parent class we can use an interface.

Top comments (0)