接口的有用用途
接口文件Gatewayinterface.php:
interface PaymentGatewayInterface
{
public function processPayment(float $amount): bool;
}
class PayPalGateway
{
public function sendPayment(float $amount): bool
{
// Send payment using PayPal API
return true;
}
}
class StripeGateway
{
public function charge(float $amount): bool
{
// Charge payment using Stripe API
return true;
}
}
创建StripePaymentAdapter.php:
class PayPalAdapter implements PaymentGatewayInterface
{
private $payPalGateway;
public function __construct(PayPalGateway $payPalGateway)
{
$this->payPalGateway = $payPalGateway;
}
public function processPayment(float $amount): bool
{
return $this->payPalGateway->sendPayment($amount);
}
}
创建PayPaladapter.php:
class StripeAdapter implements PaymentGatewayInterface
{
private $stripeGateway;
public function __construct(StripeGateway $stripeGateway)
{
$this->stripeGateway = $stripeGateway;
}
public function processPayment(float $amount): bool
{
return $this->stripeGateway->charge($amount);
}
}
现在可以通过调用接口来完成多种类型的付款:
$payPalGateway = new PayPalGateway();
$payPalAdapter = new PayPalAdapter($payPalGateway);
$payPalAdapter->processPayment(100.00); //Here PayPalAdapter's processPayment method is being called
$stripeGateway = new StripeGateway();
$stripeAdapter = new StripeAdapter($stripeGateway);
$stripeAdapter->processPayment(300.00); //Here StripeAdapter's processPayment method is being called