paysera/lib-rest-client-common

此软件包最新版本(2.7.0)没有可用的许可证信息。

REST客户端使用的基类/辅助函数

2.7.0 2023-11-15 08:27 UTC

README

RESTful API客户端的通用库

用法

您应该创建一个继承自ClientFactoryAbstractClientFactory类。在ClientFactory中,如果需要,可以覆盖任何父配置。

ClientFactory的简单示例

class TestClientFactory extends ClientFactoryAbstract
{
    const DEFAULT_BASE_URL = 'http://example.com/test/rest/v1/{locale}/';
    
    private $apiClient;

    public function __construct(array $options)
    {
        $this->apiClient = $this->createApiClient($options);
    }

    public function getTestClient()
    {
        return new TestClient($this->apiClient);
    }
}

使用此模式,您可以在不同的API中重用相同的ApiClient及其认证和其他选项。

除了ClientFactory之外,您还应该创建Client本身。最后您将使用Client本身,因此它应包含API提供的所有方法。

TestClient的简单示例

class TestClient
{
    private $apiClient;

    public function __construct(ApiClient $apiClient)
    {
        $this->apiClient = $apiClient;
    }
    
    public function withOptions(array $options)
    {
        return new TestClient($this->apiClient->withOptions($options));
    }

    /**
     * @return array
     */
    public function getSomething()
    {
        $request = $this->apiClient->createRequest(
            RequestMethodInterface::METHOD_GET,
            sprintf('/something'),
            null
        );
        return $this->apiClient->makeRequest($request);
    }
}

您应在TestClient方法中实现映射或数据转换。

示例

use Paysera\Client\CategoryClient\ClientFactory;

$clientFactory = new ClientFactory([
    'base_url' => 'custom base url',
    'auth_base_url' => 'custom auth base url',
    'basic' => [
        'username' => 'user',
        'password' => 'pass'
    ],
    'oauth' => [
        'token' => [
            'access_token' => 'your oauth access token',
            'refresh_token' => 'your oauth refresh token',
        ],
    ],
    'mac' => [
        'mac_id' => 'mac id',
        'mac_secret' => 'mac secret',
        'parameters' => [
            // list of needed parameters
        ]
    ],
    'url_parameters' => [
        'locale' => 'en',
        // list of base_url placeholder parameter values
    ],
    'headers' => [
        'Accept-Language' => 'en',
    ],
    // other configuration options
]);

$testClient = $clientFactory->getTestClient();
$data = $testClient->getSomething();
  • 请注意,仅支持单个认证机制。

如果您想在运行时更改某些配置选项,请使用TestClient::withOptions()

$factory = new TestClientFactory([
    MacAuthentication::TYPE => [
        'mac_id' => $macId,
        'mac_secret' => $macSecret,
        'parameters' => [
            'user_id' => 100,
        ]
    ]
]);

$client = $factory->getTestClient();

$client2 = $factory->getTestClient()->withOptions([
    MacAuthentication::TYPE => [
        'parameters' => ['user_id' => 999],
    ]
]);

在此,对于$client2,只有parameters中的user_id将被更改。其他配置,如mac_idmac_secret将被保持不变。