【问题标题】:Explain PHP Interface for multiple carrier support解释多运营商支持的 PHP 接口
【发布时间】:2015-07-19 15:19:01
【问题描述】:

我正在尝试设置支付网关控制器并使用来自this url 的示例。

更具体地说,这里是他们的代码示例:

// Define the interface
interface BillingProvider {
    public function charge($creditInfo);
}

// Create a Stripe implementation
class StripeBilling {
    public function charge($creditInfo)
    {
        // Stripe_Charge::charge(...);
    }
}

// Create a ServiceX implementation
class ServiceXBilling {
    public function charge($creditInfo)
    {
        // charge user with ServiceX
    }
}

然后是这个:

class PaymentController {
    protected $billing;

    public function __construct(BillingProvider $billing)
    {
        $this->billing = $billing;
    }
}

如何在项目中正确实现这一点?

我正在尝试类似的东西:

$paymentController = new PaymentController(new StripeBilling);

但随后收到错误:

Catchable fatal error: Argument 1 passed to PaymentController::__construct() must implement interface BillingProvider, instance of StripeBilling given

做一些研究,似乎 StripeBilling 和 ServiceXBilling 都应该实现 BillingProvider,这是正确的吗?

【问题讨论】:

  • class StripeBilling extends BillingProvider
  • 是的,你是对的。 class StripeBilling implements BillingProviderclass ServiceXBilling implements BillingProvider
  • 好的,谢谢。请参阅下面约翰的回答中的更多 cmets。

标签: php class interface


【解决方案1】:

具体类需要implement the interface

class StripeBilling implements BillingProvider

【讨论】:

  • 好吧,我就是这么想的。那么现在这段代码正确吗?
  • $paymentController = new PaymentController(new StripeBilling);
  • 如何调用收费方式?如果我这样做:$paymentController->charge() 我得到:Fatal error: Call to undefined method PaymentController::charge()
  • 好的,所以我在 paymentController 中创建了一个名为 charge 的公共函数,并让它调用 $this->billing->charge($creditInfo);,事情似乎按预期工作。它是否正确?如果是这样,控制器的真正意义是什么?为什么我不直接使用我的 StripeBilling 实例呢?
猜你喜欢
  • 2021-09-21
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多