Structural Patterns: Adapter, Decorator, Facade
Compose objects and simplify interfaces with structural patterns.
Composing objects
Structural patterns describe how to compose classes and objects into larger structures while keeping them flexible. We cover three workhorses:
- Adapter — make an incompatible interface usable.
- Decorator — add behavior without subclassing.
- Facade — present a simple front to a complex subsystem.
Adapter: the problem
You depend on a PaymentGateway interface, but a third-party SDK exposes chargeCard($amountInCents) with a different shape. Calling the SDK directly leaks its API everywhere. Below, the two interfaces are clearly incompatible — that mismatch is exactly what an adapter resolves.
<?php
// What our app wants to depend on
interface PaymentGateway { public function pay(float $dollars): string; }
// What the vendor actually gives us (cents, array result)
final class StripeSdk {
public function chargeCard(int $cents): array {
return ['id' => 'ch_1', 'amount' => $cents];
}
}
// dollars vs cents, string vs array -> shapes don't line up
var_dump((new StripeSdk())->chargeCard(2000));
All lessons in this course
- SOLID Principles in Practice
- Creational Patterns: Factory, Builder, Singleton
- Structural Patterns: Adapter, Decorator, Facade
- Behavioral Patterns: Strategy, Observer, Command