PHP - Interface

In advanced PHP programming, creating interfaces is a useful technique for defining a contract that classes must adhere to. An interface defines a set of method signatures that a class implementing the interface must provide. This helps ensure that classes have certain behaviors or capabilities, which can make your code more organized, maintainable, and easier to work with.

Define an Interface:

To define an interface, you use the interface keyword. Inside the interface, you declare method signatures without providing their implementation.

interface PaymentGateway {
  public function processPayment($amount);
  public function refundPayment($transactionId);
}

Implementing an Interface:

You can implement an interface in a class using the implements keyword. The implementing class must provide concrete implementations for all the methods declared in the interface.

class CreditCardGateway implements PaymentGateway {
  public function processPayment($amount) {
      // Implement the payment processing logic for credit cards
  }
  public function refundPayment($transactionId) {
      // Implement the refund logic for credit cards
  }
}

Using the Implemented Class:

You can then create an object of the class and use it as an instance of the interface.

$paymentGateway = new CreditCardGateway();
$paymentGateway->processPayment(100.00);
$paymentGateway->refundPayment("12345");

Multiple Interfaces:

A class can implement multiple interfaces by separating them with commas in the implements clause.

interface Logger {
  public function log($message);
}
class FileLogger implements Logger, PaymentGateway {
  public function log($message) {
      // Implement the logging logic to a file
  }
  public function processPayment($amount) {
      // Implement payment processing logic
  }
  public function refundPayment($transactionId) {
      // Implement refund logic
  }
}

Abstract Methods:

You can also use interfaces to declare abstract methods that all implementing classes must provide. Abstract methods don't have method bodies.

interface Logger {
  public function log($message);
}
abstract class AbstractLogger implements Logger {
  // No implementation for log() method, as it's abstract
}

Interfaces are an essential part of building flexible and extensible code in PHP. They help define clear contracts between different parts of your application and promote the use of polymorphism and abstraction to improve code maintainability and readability.