Delegation in PHP 🤝
Published Sep 16 2023
Delegation involves one object passing on a method call to another object. This allows for code reuse and flexibility in object interactions. Here's a simple example:
interface PaymentMethod {
public function transact(int $value);
}
class PayFast implements PaymentMethod {
public function transact(int $value) {
echo "Transacted R $value\n";
}
}
class Kiosk {
private $paymentMethod;
public function __construct(PaymentMethod $method) {
$this->paymentMethod = $method;
}
public function pay(int $value) {
$this->paymentMethod->transact($value);
}
}
$method = new PayFast();
$kiosk = new Kiosk($method);
$kiosk->pay(20.00);
In the above example, we have three classes. In the provided example, there are three classes. Two are concrete (PayFast
and Kiosk
), and one is an abstract interface (PaymentMethod
).
The Kiosk
class accepts a payment delegate that implements the PaymentMethod
interface. This is the class to which the payment implementation is delegated. Notice that the Kiosk
class does not concern itself with the specific implementation of the payment method. Delegation makes it easy to switch to a different payment method at runtime.
This code demonstrates a practical use of delegation in a payment system, where the Kiosk
relies on an external payment method (PayFast
) without being tightly coupled to its implementation.