ralphschindler / phetch
一个优秀的PHP HTTP客户端
dev-master
2020-10-10 18:40 UTC
Requires
- php: >=7.2
Requires (Dev)
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-11 03:35:14 UTC
README
Phetch 是 PHP 缺失的 80% 的使用案例 HTTP 客户端。Phetch 并没有发明什么新的东西,而是借鉴和构建了这些想法和需求
- API 自然、舒适、易于使用
- 类似于 Zttp 的客户端,没有 Guzzle 依赖
- 与 HTTPie 一样易于接近
- 默认使用 JSON / 合理的默认设置
- PHP 流功能(http、ssl)的轻量级包装器
- 具有浅层堆栈跟踪
- 服务容器友好
安装
$ composer require ralphschindler/phetch
用法
带有查询参数的 GET
// simple call to the Github API $resp = Phetch\Phetch::withBearerAuth('abcdefghijklmnopqrstuvwxyz0123456789') ->get('https://api.github.com/repos/ralphschindler/phetch/issues', ['state' => 'all']); $resp->json(); // the response body as an array
带有主体的 POST
$response = Phetch\Phetch::request()->post('https://api.github.com/repos/ralphschindler/phetch/issues', [ 'title' => 'My Issue', 'body' => 'This is the body to my issue', ]);
PATCH
$response = Phetch\Phetch::request()->patch('https://api.github.com/repos/ralphschindler/phetch/issues/1', [ 'title' => 'My Issue Updated Title!', ]);
DELETE,在调用时具有特殊头
// locking github issues requires a special accept header $response = Phetch\Phetch::request()->delete('https://api.github.com/repos/ralphschindler/phetch/issues/1/lock', ['headers' => ['Accept' => 'application/vnd.github.sailor-v-preview+json']] );
其他特殊帮助方法
为同一 Web 服务中的重复调用设置基本 URL
$req = Phetch\Phetch::withBaseUrl('https://api.github.com'); $respGet = $request->get(...); $respPatch = $request->patch(...);
不验证 SSL 证书
$page = Phetch\Phetch::withoutVerifying()->get('https://IDidntUpdateMyCert.org');
不跟随重定向
$page = Phetch\Phetch::withoutRedirecting()->get('https://AUrlThatRedirects.com/place');
基本认证
$page = Phetch\Phetch::withBasicAuth($username, $password)->get('https://AUrlThatRedirects.com/place');
Bearer 认证
$page = Phetch\Phetch::withBearerAuth($token)->get('https://AUrlThatRedirects.com/place');
作为应用程序内的服务
很多时候,你可能想预先配置一个请求,以便在不同的上下文中使用共享设置。此外,你可能想为特定的 Web 服务构建一个特定的客户端。
设置服务
创建服务允许你配置和共享一个 PendingRequest
对象,该对象对于你的应用程序与特定服务通信所需的所有必要的样板文件。($container
假设是某种类型的容器。)
$githubWebService = Phetch\Phetch::createService(function ($pendingRequestPrototype) { $pendingRequestPrototype->withHeaders(['User-Agent' => 'My Applications Http Client v1.0.0']) ->withBaseUrl('https://api.github.com') ->withBearerAuth('abcdefghijklmnopqrstuvwxyz0123456789'); }); $container->share('github-web-service', $githubWebService);
在你的应用程序代码的某个地方使用服务(控制器、服务类等)
PhetchService
现在包含你的典型 PendingRequest
对象,该对象已预先配置,可在应用程序的任何地方使用。每次你调用 $service->request()
时,你将获得一个克隆的/新的 PendingRequest
对象,你可以与之交互。对此新对象的状态更改不会影响服务的预先配置对象
/** @var \Phetch\PhetchService $github */ $github = $container->get('github-web-service'); // request() will always produce a fresh & pre-configured \Phetch\PendingRequest $resp = $github->request() ->get('/repos/ralphschindler/phetch/issues', ['state' => 'closed']);
待办事项
- httpie 命令解析
- 命令行 phetch 客户端
- curl 适配器(好的开源贡献会很好!)