构建类以抽象API的功能

问题描述 投票:0回答:1

我正在寻找构建一组类来处理与各种类似但竞争的API的交互。这方面的一个很好的例子是信用卡处理。我想要一个类,如应用程序开发人员使用的charge()refund()等方法,而不管商家处理器是谁。然后,我希望能够构建处理与特定商家处理器API交互的类。

所以我可能有一个与Stripe API交互,另一个与Authorize.Net交互,然后是某种类型的master或wrapper类,它从应用程序开发人员那里抽象出API特性。

在过去,我使用包装类完成了这个,我使用相同的方法(使用它们各自的API交互)为每个API创建了一个类,然后在应用程序中使用了一个包装类。用法示例可能如下所示:

$merchant = new Merchant( 'Stripe' );
$merchant->set_credentials( 'api_user', 'api_password' );
$merchant->set_cc( '4111-1111-1111-1111' );
$merchant->set_exp( '0121' );
$merchant->set_amount( 100.00 );
$merchant->charge();

使用值“Stripe”实例化此类将意味着在幕后此类将工作负载传递到适当的类以处理此交互。

我的目标是:

  • 摘要来自应用程序开发人员的API必须知道有关特定处理器的任何信息,而不是名称(因此他们可以创建类的实例),或者如果处理器更改则必须更改代码。
  • 由于我最终需要支持更多商家处理器,因此可以使用新类来处理与API的交互。

是这样做的包装类,还是PHP提供了其他更有效的机制来处理这种类型的设置?

php class wrapper
1个回答
1
投票

我将为您的内部API创建一个接口,为每个外部处理器创建一个实现,并为工厂类创建正确的实例。

代码示例(PHP 7.1):

interface MerchantInterface {
    public function set_credentials(string $username, string $password);
    public function set_cc(string $number);
    public function set_exp(string $number);
    public function set_amount(float $amount);
    public function charge();
}

class StripeMerchant implements MerchantInterface {
    public function set_credentials(string $username, string $password) {}
    public function set_cc(string $number)  {}
    public function set_exp(string $number) {}
    public function set_amount(float $amount) {}
    public function charge() {}
}

class AuthorizeNetMerchant implements MerchantInterface {
    public function set_credentials(string $username, string $password) {}
    public function set_cc(string $number)  {}
    public function set_exp(string $number) {}
    public function set_amount(float $amount) {}
    public function charge() {}
}

class MerchantFactory {
    public const MERCHANT_STRIPE = 'Stripe';
    public const MERCHANT_AUTHORIZE_NET = 'Authorize.Net';

    public static function create(string $merchant): MerchantInterface {
        switch ($merchant) {
            case self::MERCHANT_STRIPE:
                return new StripeMerchant();
            case self::MERCHANT_AUTHORIZE_NET:
                return new AuthorizeNetMerchant();
            default:
                throw new Exception('Unexpected Merchant');
        }
    }
}

$stripeMerchant = MerchantFactory::create(MerchantFactory::MERCHANT_STRIPE);
$authorizeNetMerchant = MerchantFactory::create(MerchantFactory::MERCHANT_AUTHORIZE_NET);

根据您的要求,您还可以使用构建器模式而不是工厂来创建不同的实例。建造者会照顾你的安装人员。如果你有许多可选参数(这里似乎不是这种情况)或者你想让你的商家不可变,这可能会有用。

© www.soinside.com 2019 - 2024. All rights reserved.