tiendungdev liked a comment+100 XP
4w ago
This is what made it click for me:
So $this->gateway->charge($amount); in the invoice class could be interpreted as - in case of a PaypalGateway object - as PaypalGateway ->charge(amount)?
Yes, that's correct! The line $this->gateway->charge($amount); in the Invoice class is a call to the charge method of the object that was injected into the Invoice class via its constructor.
Let's break it down step by step:
-
Dependency Injection:
- When you create an instance of the
Invoiceclass, you pass an object that implements theBillingGatewayinterface to its constructor. For example:$paypalGateway = new PaypalGateway(); $invoice = new Invoice($paypalGateway); - In this case,
$paypalGatewayis an instance of thePaypalGatewayclass, which implements theBillingGatewayinterface.
- When you create an instance of the
-
Constructor Assignment:
- Inside the
Invoiceclass constructor, the passedBillingGatewayobject is assigned to the$gatewayproperty:public function __construct(BillingGateway $gateway) { $this->gateway = $gateway; } - So,
$this->gatewaynow refers to the$paypalGatewayobject.
- Inside the
-
Method Call:
- When you call
$this->gateway->charge($amount);in thepaymethod of theInvoiceclass, it is equivalent to calling$paypalGateway->charge($amount);because$this->gatewayis the$paypalGatewayobject. - The
chargemethod of thePaypalGatewayclass will be executed with the$amountparameter.
- When you call
Example Walkthrough:
<?php
interface BillingGateway
{
public function charge($amount);
}
class PaypalGateway implements BillingGateway
{
public function charge($amount)
{
echo "Charging $amount using PayPal.\n";
}
}
class Invoice
{
private $gateway;
public function __construct(BillingGateway $gateway)
{
$this->gateway = $gateway;
}
public function pay($amount)
{
$this->gateway->charge($amount);
}
}
// Create a PaypalGateway instance
$paypalGateway = new PaypalGateway();
// Inject the PaypalGateway into the Invoice
$invoice = new Invoice($paypalGateway);
// Pay using the Invoice, which will use the PaypalGateway to charge
$invoice->pay(100);
?>
Output:
Charging 100 using PayPal.
Explanation:
- The
PaypalGatewayinstance is created and passed to theInvoiceconstructor. - The
Invoiceclass stores this instance in its$gatewayproperty. - When the
paymethod of theInvoiceclass is called with an amount, it calls thechargemethod on thePaypalGatewayinstance stored in$this->gateway. - The
chargemethod of thePaypalGatewayclass is executed, printing the message "Charging 100 using PayPal."
This demonstrates how dependency injection allows the Invoice class to use any implementation of the BillingGateway interface without being tightly coupled to a specific implementation.