DEV Community

Cover image for What is Interface and How to use it in Laravel
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on

What is Interface and How to use it in Laravel

Hello Artisan,

In object-oriented programming, an interface is a contract that specifies a set of methods that a class must implement. It defines a common set of methods that multiple classes can implement, providing a way to ensure that these classes can be used interchangeably.

In Laravel, interfaces are used to define a set of methods that a class must implement in order to satisfy a contract. They provide a way to define and enforce the implementation of specific methods across multiple classes.

  • Define the interface: Create a new interface by defining a set of methods that the implementing classes must implement. For example:

Here's an example of how to use an interface in Laravel:

<?php

namespace App\Interfaces;

interface PaymentGatewayInterface
{
    public function pay($amount);
    public function refund($transactionId, $amount);
}
Enter fullscreen mode Exit fullscreen mode
  • Implement the interface: Implement the interface by creating a new class that defines the methods specified in the interface. For example:
<?php

namespace App\Services;

use App\Interfaces\PaymentGatewayInterface;

class StripePaymentGateway implements PaymentGatewayInterface
{
    public function pay($amount)
    {
        // Implement payment gateway logic here
    }

    public function refund($transactionId, $amount)
    {
        // Implement refund logic here
    }
}

Enter fullscreen mode Exit fullscreen mode
  • Use the interface: Use the interface by creating a new instance of the class that implements the interface. For example:
<?php

namespace App\Http\Controllers;

use App\Interfaces\PaymentGatewayInterface;
use App\Services\StripePaymentGateway;

class PaymentController extends Controller
{
    public function makePayment(PaymentGatewayInterface $gateway)
    {
        $gateway->pay(100);
    }
}

// Usage:
$controller = new PaymentController();
$gateway = new StripePaymentGateway();
$controller->makePayment($gateway);

Enter fullscreen mode Exit fullscreen mode
  • In this example, the PaymentGatewayInterface interface defines the pay and refund methods that a payment gateway class must implement.

  • The StripePaymentGateway class implements this interface and provides its own implementation for the pay and refund methods.

  • Finally, the PaymentController class uses the PaymentGatewayInterface interface as a parameter type, which allows any class that implements this interface to be passed into the makePayment method.

  • This provides a way to ensure that the passed-in class meets the requirements of the interface.

In this way we can use interfaces in laravel.

Thank You!!

Happy Reading... ❤️ 🦄

Top comments (0)