How to use PHP Interface in Laravel?

PHP interfaces are a blueprint of a class, that defines a set of methods that must be implemented in the class that implements the interface. The interface allows you to define what methods a class should implement without providing the actual implementation, which enforces a contract between different classes and ensures that they have a common set of methods.

Declaration of an interface requires, the usage of the keyword “interface” followed by the interface name and a block of method signatures.

Let’s look at an example(PHP/Laravel):

PaymentGatewayInterface.php
Create an interface that specifies the required methods.

<?php
namespace App\Interfaces;

interface PaymentGatewayInterface {
    public function pay($amount);
    public function refund($paymentId, $amount);
}

PaypalPaymentGateway.php
Now let’s implement the interface by creating a new class that defines the methods specified in the interface.

<?php
namespace App\Services;

use App\Interfaces\PaymentGatewayInterface;

class PaypalPaymentGateway implements PaymentGatewayInterface
{
    public function pay($amount)
    {
        // Implementation of payment gateway logic here
    }

    public function refund($paymentId, $amount)
    {
        // Implementation of refund logic here
    }
}

AppServiceProvider.php

Before you use this interface in the controller, let’s register it in AppServiceProvider.

<?php

namespace App\Providers;

use App\Interfaces\PaymentGatewayInterface;
use App\Services\PaypalPaymentGateway;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->bind(PaymentGatewayInterface::class, PaypalPaymentGateway::class);
    }
}

PaymentController.php

Use the interface by creating a new instance of the class that implements the interface

<?php

namespace App\Http\Controllers;

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

class PaymentController extends Controller
{
    protected PaymentGatewayInterface $gatewayService;

    public function __construct(PaymentGatewayInterface $gatewayService) {
        $this->gatewayService = $gatewayService;
    }

    public function makePayment()
    {
        $this->gatewayService->pay(100);
    }
}

That’s it, this was the simplest way of implementing the interface in PHP/Laavel.

Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk