承接 friendsofhyperf/http-client 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

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 我们能提供哪些服务?
定制开发 / 二次开发

基于 friendsofhyperf/http-client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 46.04k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 13
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-06-17