friendsofhyperf/http-client
Composer 安装命令:
composer require friendsofhyperf/http-client
包简介
The http client component for Hyperf, from Laravel.
README 文档
README
An HTTP client component for Hyperf, ported from Laravel and backed by Guzzle.
Installation
composer require friendsofhyperf/http-client guzzlehttp/guzzle:^7.6
guzzlehttp/guzzle is a suggested dependency of this package and is required to send
requests. No configuration file needs to be published.
Sending Requests
Use the Http facade to send GET, HEAD, POST, PUT, PATCH, and DELETE
requests. Request bodies are sent as JSON by default.
use FriendsOfHyperf\Http\Client\Http; $response = Http::get('https://example.com/users', [ 'page' => 1, ]); $response = Http::post('https://example.com/users', [ 'name' => 'Taylor', ]);
Configure a pending request by chaining methods before the HTTP verb:
$response = Http::baseUrl('https://example.com') ->withToken('token') ->acceptJson() ->timeout(10) ->connectTimeout(3) ->withHeaders(['X-Trace-Id' => 'trace-id']) ->withUrlParameters(['user' => 1]) ->get('/users/{user}', ['active' => true]);
Use withUrlParameters() to expand URI template placeholders. Use asForm(),
attach(), or withBody() for form, multipart, or raw request bodies:
$response = Http::withUrlParameters(['user' => 1]) ->get('https://example.com/users/{user}'); $response = Http::asForm()->post('https://example.com/login', [ 'email' => 'taylor@example.com', ]); $response = Http::attach('avatar', fopen('/path/to/avatar.jpg', 'r'), 'avatar.jpg') ->post('https://example.com/users/1/avatar');
The default connect timeout is 10 seconds and the default request timeout is 30
seconds. Other Guzzle request options may be supplied with withOptions(). Use
withoutVerifying() only when intentionally disabling TLS certificate verification.
Retries
retry() accepts either the total number of attempts or an array of backoff delays in
milliseconds. Its second argument may be a fixed delay or a closure. The optional
third argument decides whether a failed response or connection exception should be
retried.
use FriendsOfHyperf\Http\Client\PendingRequest; use Throwable; $response = Http::retry( [100, 200], 0, fn (Throwable $exception, PendingRequest $request) => true, )->get('https://example.com');
By default, exhausted retries throw an exception. Pass false as the fourth argument
to return the final failed response instead.
Responses and Errors
Requests return FriendsOfHyperf\Http\Client\Response. Common response methods
include:
$response->body(); $response->json(); $response->json('user.name'); $response->object(); $response->collect(); $response->fluent(); $response->header('Content-Type'); $response->headers(); $response->status(); $response->effectiveUri(); $response->successful(); $response->redirect(); $response->failed(); $response->clientError(); $response->serverError();
HTTP 4xx and 5xx responses do not throw by default. Call throw() on the pending
request or response to throw RequestException. Connection failures throw
ConnectionException.
use FriendsOfHyperf\Http\Client\RequestException; try { $response = Http::get('https://example.com/users/1')->throw(); } catch (RequestException $exception) { $response = $exception->response; }
Concurrent Requests
Use pool() to send requests concurrently. Use as() to assign response keys.
use FriendsOfHyperf\Http\Client\Http; use FriendsOfHyperf\Http\Client\Pool; $responses = Http::pool(function (Pool $pool) { return [ $pool->as('user')->get('https://example.com/users/1'), $pool->as('posts')->get('https://example.com/posts'), ]; }); $responses['user']->status();
Testing
fake() intercepts matching requests and records them for assertions. Call
preventStrayRequests() to reject requests without a matching fake.
use FriendsOfHyperf\Http\Client\Http; use FriendsOfHyperf\Http\Client\Request; Http::preventStrayRequests(); Http::fake([ 'example.com/users/*' => Http::response(['name' => 'Taylor'], 200), ]); $response = Http::get('https://example.com/users/1'); Http::assertSent(fn (Request $request) => $request->url() === 'https://example.com/users/1'); Http::assertSentCount(1);
Use a response sequence when repeated requests should receive different responses.
An exhausted sequence throws OutOfBoundsException unless whenEmpty() or
dontFailWhenEmpty() is configured.
Http::fakeSequence('example.com/*') ->push(['result' => 'first']) ->pushStatus(404);
Other available assertions include assertNotSent(), assertNothingSent(),
assertSentInOrder(), and assertSequencesAreEmpty().
Middleware and Events
Add per-request middleware with withMiddleware(), withRequestMiddleware(), or
withResponseMiddleware(). Factory also provides globalMiddleware(),
globalRequestMiddleware(), and globalResponseMiddleware().
When the Factory is created with a PSR event dispatcher, it dispatches
RequestSending, ResponseReceived, and ConnectionFailed events.
Laravel Compatibility
The API is based on Laravel's HTTP client, but the available API and behavior are defined by this component's source code. Consult the Laravel HTTP Client documentation for additional background, and verify APIs against this component before using them.
friendsofhyperf/http-client 适用场景与选型建议
friendsofhyperf/http-client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 46.04k 次下载、GitHub Stars 达 5, 最近一次更新时间为 2021 年 06 月 17 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「hyperf」 「v3.2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 friendsofhyperf/http-client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 friendsofhyperf/http-client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 friendsofhyperf/http-client 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
The model morph addon for Hyperf.
The MySqlGrammar addon for Hyperf.
The Data Transfer Objects with validation for Hyperf.
An async event for hyperf.
An elegant debug assistant for the hyperf framework.
The Notification for Hyperf.
统计信息
- 总下载量: 46.04k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 5
- 点击次数: 13
- 依赖项目数: 2
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-06-17