Skip to main content

Interfaces

Chapter Overview

In this chapter you will learn:

  • What interfaces are
  • Why interfaces exist
  • Interface syntax
  • Implementing interfaces
  • Multiple interfaces
  • Interface inheritance
  • Real-world examples
  • Dependency Injection
  • SOLID principles
  • PocketMine examples
  • Enterprise architecture
  • Best practices
  • Interview questions
  • Exercises and projects

What is an Interface?

An Interface is a contract.

It tells classes:

"If you implement me,
you MUST provide these methods."

Real Life Example

Think of a charger.

Your phone only cares:

Can this charger provide power?

It does not care:

  • Brand
  • Company
  • Internal circuitry
  • Manufacturing process

As long as it follows the contract.

This is exactly how interfaces work.


Definition

An interface defines:

WHAT a class must do
but NOT HOW it should do it.

Example

interface Animal {

public function sound();

}

This means:

Every class implementing:

Animal

must provide:

sound()

Implementation

class Dog
implements Animal {

public function sound() {

echo "Bark";

}

}

class Cat
implements Animal {

public function sound() {

echo "Meow";

}

}

Visualization

Animal Interface

┌─────────────┐
│ sound() │
└─────────────┘
/ \
/ \
Dog Cat

Why Interfaces Exist

Without interfaces:

class PayPal {

}

class Stripe {

}

class Crypto {

}

Every class becomes different.

No common contract.


With interfaces:

interface PaymentGateway {

public function pay(
float $amount
);
}

Now every payment system works similarly.


Basic Syntax


Declaring Interface

interface Logger {

public function log(
string $message
): void;

}

Implementing Interface

class FileLogger
implements Logger {

public function log(
string $message
): void {

echo $message;

}

}

Rules of Interfaces


1. Methods Are Public

Invalid:

protected function log();

Interfaces only allow:

public

2. Cannot Instantiate

Invalid:

new Logger();

Error.


3. Cannot Have Properties

Invalid:

interface Test {

public string $name;

}

4. Methods Have No Body

Invalid:

interface Test {

public function hello() {

}

}

Why?

Because interfaces only define:

CONTRACTS

not implementations.


Example


Interface

interface Shape {

public function area();

}

Circle

class Circle
implements Shape {

public function area() {

return 50;

}

}

Square

class Square
implements Shape {

public function area() {

return 100;

}

}

Polymorphism

Interfaces become extremely powerful with polymorphism.

Example:

function calculate(
Shape $shape
) {

return
$shape->area();

}

Can accept:

  • Circle
  • Square
  • Rectangle

Real World Example


Payment Gateway

Interface:

interface PaymentGateway {

public function pay(
float $amount
);

}

Stripe

class StripeGateway
implements PaymentGateway {

public function pay(
float $amount
) {

}

}

PayPal

class PaypalGateway
implements PaymentGateway {

public function pay(
float $amount
) {

}

}

Crypto

class CryptoGateway
implements PaymentGateway {

public function pay(
float $amount
) {

}

}

Usage

function processPayment(
PaymentGateway $gateway
) {

$gateway->pay(
500
);

}

Amazing flexibility.


Visualization

PaymentGateway

├── PayPal
├── Stripe
└── Crypto

Logger Example


Interface

interface Logger {

public function log(
string $message
);
}

Implementations

FileLogger
DiscordLogger
DatabaseLogger
ConsoleLogger

Usage

class UserService {

public function __construct(
private Logger $logger
) {

}

}

This is Dependency Injection.


Why Interfaces Matter

Imagine changing:

File Logger

to:

Discord Logger

No code changes.

Simply swap implementation.


Database Example


Interface

interface Database {

public function query(
string $sql
);

}

Implementations

MySQLDatabase
SQLiteDatabase
MongoDatabase
RedisDatabase

Application never changes.


Multiple Interfaces

PHP allows implementing multiple interfaces.


Example:

class User
implements
JsonSerializable,
ArrayAccess,
Countable {

}

Visualization

User

├── JsonSerializable
├── ArrayAccess
└── Countable

Why Multiple Interfaces?

Because PHP does not support:

Multiple Inheritance

Interfaces solve this problem.


Interface Inheritance

Interfaces can extend other interfaces.


Example:

interface Animal {

public function eat();

}

interface Dog
extends Animal {

public function bark();

}

Implementation:

class GermanShepherd
implements Dog {

public function eat() {

}

public function bark() {

}

}

Visualization

Animal

Dog

GermanShepherd

Interface Segregation Principle

One huge interface is bad.

Bad:

interface Worker {

work();
eat();
sleep();
code();
drive();
}

Many classes won't need all methods.


Good:

interface Worker {

work();

}
interface Driver {

drive();

}

Small interfaces are better.


Real Enterprise Architecture

Controller

Service

Repository Interface

Database Implementation

Example:

UserRepositoryInterface

Implementations:

MysqlRepository
MongoRepository
RedisRepository

PocketMine Examples

PocketMine uses interfaces heavily.


CommandSender

Player
Console
Remote Console

All implement:

CommandSender

Plugin can do:

function execute(
CommandSender $sender
)

Works everywhere.


InventoryHolder

Implemented by:

Player
Chest
Hopper
Furnace

ChunkLoader

Implemented by:

Player
World Systems
Plugins

Why?

Because interfaces create:

Loose Coupling

Tight Coupling

Bad:

class UserService {

private MysqlDatabase $db;

}

Cannot change database.


Loose Coupling

Good:

private DatabaseInterface $db;

Any implementation works.


Dependency Injection Example


Bad:

$this->logger =
new FileLogger();

Good:

public function __construct(
Logger $logger
)

Now:

FileLogger
DiscordLogger
DatabaseLogger

all work.


Open Closed Principle

Interfaces help us follow:

Open for Extension
Closed for Modification

Add new classes.

Do not modify existing code.


Laravel Examples


Cache

Cache Interface

├── Redis
├── Memcached
└── File

Queue

Queue Interface

├── Redis
├── Database
└── SQS

Mail

Mailer Interface

├── SMTP
├── Mailgun
└── SES

PocketMine Architecture Example

CommandSender

├── Player
├── ConsoleCommandSender
└── RconCommandSender

One API.

Many implementations.


Benefits


1. Loose Coupling

Classes depend on contracts.

Not implementations.


2. Easier Testing

Example:

FakeDatabase

can replace:

MysqlDatabase

3. Better Architecture

Large projects remain organized.


4. Easy Extensions

Add new features without changing code.


Common Beginner Mistakes


Creating Giant Interfaces

Bad.


Naming Interface Poorly

Bad:

interface ManagerInterfaceFactoryHandler

Good:

Logger
PaymentGateway
Notifier

Depending On Implementations

Bad:

private MysqlDatabase $db;

Good:

private Database $db;

Best Practices

✅ Small interfaces.

✅ Depend on abstractions.

✅ Keep contracts simple.

✅ Use interfaces everywhere in large projects.


Exercises


Exercise 1

Create:

Animal Interface

Methods:

sound()
eat()

Exercise 2

Create:

PaymentGateway

Implement:

PayPal
Stripe
Crypto

Exercise 3

Create:

Notifier

Implement:

Email
Discord
SMS

Mini Project

Create:

ZyroNetwork Logger System

Interface:

Logger

Implement:

FileLogger
DiscordLogger
ConsoleLogger

Inject logger everywhere.


Interview Questions


What is an interface?

A contract defining methods classes must implement.


Can interfaces contain properties?

No.


Can interfaces have implementations?

No.


Can a class implement multiple interfaces?

Yes.


Why are interfaces important?

Because they provide loose coupling and scalability.


Summary

Interfaces provide:

✅ Contracts

✅ Loose Coupling

✅ Dependency Injection

✅ Better Testing

✅ Enterprise Architecture

✅ Framework Flexibility


References

https://www.php.net/manual/en/language.oop5.interfaces.php


Next Chapter

➡ Abstract Classes

➡ Traits

➡ Dependency Injection

➡ SOLID Principles