The "Adapter" pattern in programming is a design pattern that falls under the category of structural patterns. Its main purpose is to allow objects with incompatible interfaces to work together. This pattern is applied when there is a need to interact between classes with different interfaces, and directly changing these interfaces is not possible, but there is a requirement for interaction between them.
In the context of PHP, consider a situation where there is an existing class `OldClass` with the `oldMethod`, and we want to use it in a context where a different interface is expected. We can use the "Adapter" pattern to create an adapter class that provides the required interface and utilizes the functionality of `OldClass`.
// Existing class with an incompatible interface
class OldClass {
public function oldMethod() {
return "Old method";
}
}
// Interface expected in the context
interface NewInterface {
public function newMethod();
}
// Adapter class that allows using OldClass in a new context
class Adapter implements NewInterface {
private $oldInstance;
public function __construct(OldClass $oldInstance) {
$this->oldInstance = $oldInstance;
}
public function newMethod() {
// Calling oldMethod, adapting it to the new interface
return $this->oldInstance->oldMethod();
}
}
// Using the adapter class
$oldObj = new OldClass();
$adapter = new Adapter($oldObj);
$result = $adapter->newMethod();
echo $result; // Output: "Old method"
In this example, Adapter creates a bridge between `OldClass` and `NewInterface`, allowing the use of `OldClass` functionality through the new interface.