Api Wrappers的类组织

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

我正在努力学习为第三方api创建php包装器。但是我对实现多个扩展/相互实现的类感到困惑。

class Api {
   protected $username;
   protected $password;
   protected $wsdl = "http://example.com"

   protected $client;
   protected $account;

   public function __construct($username, $password)
   {
       $this->client = new SoapClient($this->wsdl);
       $authData = [
           "Credentials"   => [
               "Username"          => $username,
               "Password"          => $password
           ]
       ];

       $this->makeCall('AuthenticateUser', $authData);
       $this->account = $this->makeCall('GetAccountInfo', ["Authenticator" => $this->authenticator]);
   }

   protected function makeCall($method, $data) {
       $result = $this->client->$method($data);
       $this->authenticator = $result->Authenticator;
       return $result;
   }
}

直到这里,它才有意义。但是,此时我不想在此类中添加所有方法。因此,我决定为每个方法创建一个单独的类。在那里,问题开始了。

class AddressValidator extends Api
{
    public function validateAddress($data) {
       $response = $this->makeCall('validateAddress', $data);
       dd($response);
    }
}

从逻辑上讲,我需要如何调用包装器(在我的控制器中)如下所示,对吧?

$api = new Api($username, $password);
$api->validateAddress($params);   // but I can't call this line with this setup

相反,这有效:

$api = new ValidateAddress($username, $password);
$api->validateAddress($params);

有道理,但这是组织它的好方法吗?

设置api包装器的美妙方法是什么?顺便说一句,也许这种方法完全错了。我很高兴听到你的想法

php laravel api wrapper
2个回答
1
投票

您可以使用特征来组织方法,而不是扩展您的API类。

    class Api {
        use ValidateAddressTrait;

        ...
    }

特征:

    trait ValidateAddressTrait {
        public function validateAddress($data) {
            $response = $this->makeCall('validateAddress', $data);
            dd($response);
        }
    }

使用:

    $api = new Api($username, $password);
    $api->validateAddress($params);

这并不是特质的意图,但我认为它可以为您提供所需的结果。


1
投票

也许是这样的

class Api {
    private $class;
       .
       .
    public function __construct($username, $password, $class_name) {
        .
        .
        $this->class = new $class_name();
    }

    public function ApiCall($func, ...$arguments) {
        $this->class->$func($arguments);
    }
}

我不确定这是否会让事情变得更容易,但它确实有效。

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