Software systems sometimes face the compatibility issue, when the output of one system may not conform with the expected input of another system, in this cases we use a adapter.
Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.
The adapter essentially encapsulates the adaptee and presents a new interface, or appearance, to the client class. It does this by wrapping the adaptee’s interface and exposing a new target interface that makes sense to the client.
<?php
// --- Target Interface --- //
// The interface the client expects.
interface LoggerInterface {
public function log(string $level, string $message): void;
}
// --- Adaptee --- //
// Existing class with an incompatible interface.
class LegacyLogger {
public function writeLog(string $text): void {
echo "Legacy log: $text\n";
}
}
// --- Adapter --- //
// The Adapter makes the Adaptee compatible with the Target interface.
class LegacyLoggerAdapter implements LoggerInterface {
private LegacyLogger $legacyLogger;
public function __construct(LegacyLogger $legacyLogger) {
$this->legacyLogger = $legacyLogger;
}
public function log(string $level, string $message): void {
// Convert the expected format into what the legacy system understands.
$formattedMessage = strtoupper($level) . ": " . $message;
$this->legacyLogger->writeLog($formattedMessage);
}
}
// --- Concrete Class (for comparison) --- //
// A modern JSON logger that already matches the interface.
class JsonLogger implements LoggerInterface {
public function log(string $level, string $message): void {
echo json_encode(['level' => $level, 'message' => $message], JSON_PRETTY_PRINT) . "\n";
}
}
// --- Client Code --- //
function clientCode(LoggerInterface $logger): void {
$logger->log('info', 'Adapter pattern in action!');
}
// Use the modern logger
echo "Using JsonLogger:\n";
clientCode(new JsonLogger());
// Use the legacy logger via adapter
echo "\nUsing LegacyLogger through Adapter:\n";
$legacyAdapter = new LegacyLoggerAdapter(new LegacyLogger());
clientCode($legacyAdapter);
//Output
//Using JsonLogger
{
"level": "info",
"message": "Adapter pattern in action!"
}
//Using LegacyLogger through Adapter
Legacy log: INFO: Adapter pattern in action!
Leave a Reply