haveapi/client

基于HaveAPI的API客户端

0.22.0 2024-03-14 14:44 UTC

README

haveapi-client-php 是基于 HaveAPI 的API的PHP客户端。

要求

安装

可以使用composer安装haveapi-client-php,将 haveapi/client 添加到您的 composer.json

{
	"require": {
		"haveapi/client": "*"
	}
}

您也可以克隆此存储库并使用PSR-4兼容的自动加载器,或包含 bootstrap.php,它将加载所有必要的类。当使用存储库时,您必须自己安装Httpful。

使用方法

首先查看API文档,了解其工作原理和可用的资源/操作。

创建客户端实例

$api = new \HaveAPI\Client("http://your.api.tld");

使用HTTP基本认证

$api->authenticate('basic', ['user' => 'yourname', 'password' => 'password']);

使用令牌认证

$api->authenticate('token', ['user' => 'yourname', 'password' => 'password']);

当使用令牌认证时,通常需要保存令牌以供以后使用

$token = $api->getAuthenticationProvider()->getToken();

下次,使用之前收到的令牌进行认证

$api->authenticate('token', ['token' => $token]);

作为数组索引访问资源和操作

$api['vps']['index']->call();
$api['vps']['show']->call(101);

$api['vps.index']->call();
$api['vps.show']->call(101);

作为属性/方法访问资源和操作

$api->vps->list();

可以向资源和/或操作提供参数。

$api->vps->find(101);
$api->vps->ip_address->delete(101, 10);

$api->vps(101)->find();
$api->vps(101)->ip_address(10)->delete();
$api->vps(101)->ip_address->delete(10);

参数

参数作为数组传递给操作。这是传递给操作的最后一个参数。对象ID必须在其前面。

$api->vps->create([
	'hostname' => 'myhostname',
	'template' => 1
]);

$api->vps->ip_address->create(101, ['version' => 4]);
$api->vps(101)->ip_address->create(['version' => 4]);

对象行为

获取现有资源

$vps = $api->vps->find(101);
echo $vps->id . "<br>";
echo $vps->hostname . "<br>";
$vps->hostname = 'gotcha';
$vps->save();

创建新实例

$vps = $api->vps->newInstance();
$vps->hostname = 'new vps';
$vps->save();
echo $vps->id . "<br>";

资源列表

$vpses = $api->vps->list();

foreach($vpses as $vps) {
	echo $vps->id ." = ". $vps->hostname ."<br>";
}

响应

如果操作不返回对象或对象列表,则返回 \HaveAPI\Client\Response 类。

$vps = $api->vps->find(101);
$response = $vps->custom_action();

print_r($response->getResponse());

参数可以直接访问

echo $response['hostname'];

错误处理

如果操作失败,则抛出异常 \HaveAPI\Client\Exception\ActionFailed。认证错误会导致抛出异常 \HaveAPI\Client\Exception\AuthenticationFailed

try {
	$api->vps->create();

} catch(\HaveAPI\Client\Exception\ActionFailed $e) {
	echo $e->getMessage();
	print_r($e->getErrors());
}

尝试访问不存在资源和操作时,抛出异常 \HaveAPI\Client\Exception\ObjectNotFound。另外,调用没有所有必要参数(对象ID)的操作会导致抛出 \HaveAPI\Client\Exception\UnresolvedArguments 异常。

客户端抛出的所有异常都是 \HaveAPI\Client\Exception\Base 的子类。

文档

https://projects.vpsfree.cz/haveapi-client-php/ref/

许可

haveapi-client-php 在MIT许可下发布。