dcarbone/php-consul-api

Consul HTTP API 的 PHP 客户端

v2.0.0 2024-02-11 03:10 UTC

README

Tests

Consul HTTP API 的 PHP 客户端

这个库松散地基于 官方 GO 客户端

版本兼容性

API 库的新版本可能与较旧的 Consul 版本在有限范围内工作,但没有任何保证,并且不会解决向后兼容性问题。

Composer

这个库旨在与 Composer 一起使用

要求条目

{
    "require": {
        "dcarbone/php-consul-api": "^v2.0"
    }
}

配置

首先,构建一个 Config。这个类与Config Struct非常相似,存在于Consul API 子包中。

默认配置

如果你在主机上定义了一些Consul 环境变量,则执行以下操作可能最简单

$config = \DCarbone\PHPConsulAPI\Config::newDefaultConfig();

高级配置

你也可以自行定义值

$config = new \DCarbone\PHPConsulAPI\Config([
    'HttpClient' => $client,            // [required] Client conforming to GuzzleHttp\ClientInterface
    'Address' => 'address of server',   // [required]

    'Scheme' => 'http or https',            // [optional] defaults to "http"
    'Datacenter' => 'name of datacenter',   // [optional]
    'HttpAuth' => 'user:pass',              // [optional]
    'WaitTime' => '0s',                     // [optional] amount of time to wait on certain blockable endpoints.  go time duration string format. 
    'Token' => 'auth token',                // [optional] default auth token to use
    'TokenFile' => 'file with auth token',  // [optional] file containing auth token string
    'InsecureSkipVerify' => false,          // [optional] if set to true, ignores all SSL validation
    'CAFile' => '',                         // [optional] path to ca cert file, see http://docs.guzzlephp.org/en/latest/request-options.html#verify
    'CertFile' => '',                       // [optional] path to client public key.  if set, requires KeyFile also be set
    'KeyFile' => '',                        // [optional] path to client private key.  if set, requires CertFile also be set
    'JSONEncodeOpts'=> 0,                   // [optional] php json encode opt value to use when serializing requests
]);

配置说明

默认情况下,此客户端将尝试定位一系列环境变量来描述上述大部分配置属性。有关该列表,请参阅此处,有关环境变量名称的列表,请参阅此处

对于更高级的客户端配置,例如代理配置,您必须在构建 PHPConsulAPI Config 对象之前构建自己的 GuzzleHttp 客户端。

例如

$proxyClient = new \GuzzleHttp\Client(['proxy' => 'whatever proxy you want']]);
$config = new \DCarbone\PHPConsulAPI\Config([
    'HttpClient' => $proxyClient,
    'Address' => 'address of server',
]);

在构建客户端时,如果您直接使用或使用其派生的 GuzzleHttp\Client 对象,您可以传递 Guzzle 请求选项 中的任何选项。

Consul

接下来,构建一个 Consul 对象

$consul = new \DCarbone\PHPConsulAPI\Consul($config);

注意:如果您没有创建自己的配置对象,Consul 将使用 Config::newDefaultConfig() 创建自己的配置对象,并尝试找到合适的 HTTP 客户端。

构建完成后,您可以通过相应的客户端类与每个 Consul API 进行交互

$kvResp = $consul->KV->Keys();
if (null !== $kvResp->Err) {
    die($kvResp->Err);
}

var_dump($kvResp->Value);

...例如。

当前客户端

随着时间的推移,将添加更多!

测试

测试套件仍处于初期阶段,但它正在直接针对实际的Consul代理进行测试。将在时间允许的情况下进行补充。未来的计划是建立一个简单的集群,以提供更接近现实世界的测试场景。