DEV Community

Aleson França
Aleson França

Posted on

Adapter Pattern in PHP

What is the Adapter pattern?

The Adapter is a structural pattern from the GoF (Gang Of Four) catalog. It allows classes with incompatible interfaces to work together.

It acts like a "translate" between two interfaces.

This is very useful when you need to integrate a library or and old system into your modern app without changing the original code.


Classic Problem

Imagine you use a library to send SMS, but your system only works with the NotificationInterface

interface NotificationInterface {
    public function send(string $to, string $message): bool;
}
Enter fullscreen mode Exit fullscreen mode

But the library you want to use offers this class:

class SmsService {
    public function sendSms(string $phoneNumber, string $text): bool {
        // Sending logic
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

The method names and parameters are different! You can't replace one with the other directly.
Here is where the Adapter helps!


Solution: creating an adapter

We create a class that implements the expected interface and delegates the call to the library.

class SmsAdapter implements NotificationInterface
{
    private SmsService $smsService;

    public function __construct(SmsService $smsService)
    {
        $this->smsService = $smsService;
    }

    public function send(string $to, string $message): bool
    {
        // Adapt the call
        return $this->smsService->sendSms($to, $message);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, any part of the system that depends on NotificationInterface can use SmsAdapter easily:

$smsService = new SmsService();
$notification = new SmsAdapter($smsService);

$notification->send('+5511999999999', 'Hi, you have a new message!');
Enter fullscreen mode Exit fullscreen mode

Benefits of using Adapter

  • Decoupling: Your system dependes only on the interface, not on the concrete class.
  • Reuse: Integrate old systems or third-part libraries without changing their code.
  • Maintenance: It is easier to replace or update dependencies in the future.

When not to use it

  • If you can change the library, maybe it is better to make the interface match directly.
  • If you need to adapt many methods, maybe you should rethink your architecture.

Top comments (0)