mostka / hal-client
一个轻量级的客户端,用于消费和操作超文本应用语言(HAL)资源。
dev-main
2024-03-28 11:16 UTC
Requires
- php: ^8.1||^8.2||^8.3
- ext-json: *
- guzzlehttp/psr7: ^2.6.2
- guzzlehttp/uri-template: ^1.0
- php-http/discovery: ^1.19
- php-http/guzzle7-adapter: ^0.1.1
- php-http/message: ^1.16
- php-http/message-factory: ^1.0@dev
- psr/http-client: ^1.0
- psr/http-factory-implementation: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.1
- phpunit/phpunit: ^8.1
- symfony/http-client: 6.4.*
Suggests
- guzzlehttp/guzzle: For using Guzzle as your HTTP client
This package is not auto-updated.
Last update: 2024-09-27 11:53:48 UTC
README
一个用于消费和操作 超文本应用语言(HAL) 资源的轻量级PHP客户端。
安装
使用 Composer 安装最新版本。
composer require jsor/hal-client
请访问 Packagist 页面 查看所有可用版本。
HTTP客户端依赖
Hal客户端需要一个 HttpClientInterface 实现,该实现可以处理 PSR-7 请求和响应。
要使用此库中提供的默认实现,您需要安装Guzzle 7、6或5。
composer require guzzlehttp/guzzle:"^5.0||^6.0||^7.0"
使用方法
我们将使用 Propilex 作为示例API端点。
创建客户端
首先,我们设置一个 HalClient 实例。
use Jsor\HalClient\HalClient; $client = new HalClient('http://propilex.herokuapp.com');
现在我们可以设置额外的标头(例如,一个认证标头),这些标头将随每个请求一起发送。
$client = $client->withHeader('Authorization', 'Bearer 12345');
请注意,客户端实例是 不可变对象,这意味着,任何更改实例状态的调用都会返回一个 新 实例,而不会更改原始实例。
// Wrong! $client->withHeader('Authorization', '...'); $resource = $client->get('/protected'); // Correct! $client = $client->withHeader('Authorization', '...'); $resource = $client->get('/protected');
浏览API
要开始浏览API,我们首先获取根资源。
/** @var \Jsor\HalClient\HalResource $rootResource */ $rootResource = $client->root();
现在我们跟随 p:documents 链接。
/** @var \Jsor\HalClient\HalLink $documentsLink */ $documentsLink = $rootResource->getFirstLink('documents'); $documentsResource = $documentsLink->get(); $totalDocuments = $documentsResource->getProperty('total'); foreach ($resource->getResource('documents') as $document) { echo $document->getProperty('title') . PHP_EOL; }
如果有包含更多文档的第二页,我们可以跟随 next 链接。
if ($documentsResource->hasLink('next')) { $nextDocumentsResource = $documentsResource->getFirstLink('next')->get(); }
好的,让我们创建一个新的文档。
$newDocument = $documentsResource->post([ 'body' => [ 'title' => 'Sampl document', 'body' => 'Lorem ipsum' ] ]);
糟糕!文档标题中有个拼写错误。我们来修复它。
$changedDocument = $newDocument->put([ 'body' => [ 'title' => 'Sampe document', 'body' => $newDocument->getProperty('body') ] ]);
太糟糕了,我们放弃了。
$changedDocument->delete();
许可证
版权所有(c)2015-2021 Jan Sorgalla。在 MIT 许可证 下发布。