strictphp/http-clients 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

strictphp/http-clients

Composer 安装命令:

composer create-project strictphp/http-clients

包简介

Various http client implementations for better developer and devops experience.

README 文档

README

The HTTP Clients package provides a collection of HTTP clients that can be used to manage HTTP requests and responses in your PHP application. The package includes a ClientsFactory to simplify the creation of clients by allowing you to define a list of ClientFactoryContract implementations.

Features

  • Uses PSR container for dependency injection.
  • CacheResponseClient: Utilizes PSR-6 (simple-cache) for caching responses, improving development speed by serving cached responses for subsequent requests.
  • CustomizeRequestClient: You can modify the request before sending it.
  • EventClient: Dependent on PSR-14 (event-dispatcher) and enables you to attach events before, during, or after a request, which is useful for logging or other actions.
  • MainClient: First middleware.
  • MockClient: Prepared for tests.
  • RetryClient: If the call sendRequest throw exception, it tries to send request once more.
  • SleepClient: Allows you to introduce a wait interval between requests, which may be necessary for interacting with external APIs that require rate limiting.
  • StoreClient: Save your REQuests as PHPStorm REQ.http file and corresponding RESponse as a file with suffix RES.<code>.[headers|xml|txt|json|html|pdf].

Integration

Installation

You can install the HTTP Clients package via Composer:

composer require strictphp/http-clients

Usage

The ClientsFactory simplifies the creation of clients by allowing you to define a list of ClientFactoryContract implementations with dependency injection.

Example:

use Psr\Container\ContainerInterface;
use Psr\Http\Client\ClientInterface;
use StrictPhp\HttpClients\Clients\CacheResponse\CacheResponseClientFactory;
use StrictPhp\HttpClients\Clients\CustomizeRequest\CustomizeRequestClientFactory;
use StrictPhp\HttpClients\Clients\Event\EventClientFactory;
use StrictPhp\HttpClients\Clients\Retry\RetryClientFactory;
use StrictPhp\HttpClients\Clients\Sleep\SleepClientFactory;
use Strictphp\HttpClients\Factories\ClientsFactory;
use Strictphp\HttpClients\Iterators\FactoryToServiceIterator;

// Assuming $client is the main client like GuzzleHttp\Client
/** @var ClientInterface $client */
/** @var ContainerInterface $container */

// the order of classes is important, see image below
$clients = [
    CacheResponseClientFactory::class, // used like first
    RetryClientFactory::class,
    SleepClientFactory::class,
    EventClientFactory::class,
    CustomizeRequestClientFactory::class,
    // Other client factories...
];

/**
 * This iterator change array<class-string<ClientFactoryContract>> to array<ClientFactoryContract>
 */
$toService = new FactoryToServiceIterator($container, $clients);

$clientFactory = new ClientsFactory($client);
$client = $clientFactory->create($toService);
// Alternatively, you can use second parameter of constructor:
$clientFactory = new ClientsFactory($client, $toService);
$client = $clientFactory->create();

These examples demonstrate how to efficiently manage HTTP requests and responses in your PHP application using the provided HTTP client classes and the ClientsFactory.

image

ConfigManager

Config manager is designed for setting different configuration per host (IP, domain). Each HTTP client can contain Config class in their namespace.

Setting up default configuration

use StrictPhp\HttpClients\Managers\ConfigManager;
use StrictPhp\HttpClients\Clients\Sleep;

// set up for SleepClient
$config = new Sleep\SleepConfig(1000, 2000);

/** @var ConfigManager $configManager */
$configManager->addDefault($config);

Setting up override for given domain

use StrictPhp\HttpClients\Managers\ConfigManager;
use StrictPhp\HttpClients\Clients\Sleep;

// set up for SleepClient
$config = new Sleep\SleepConfig(1000, 2000);

/** @var ConfigManager $configManager */
$configManager->add('strictphp.com', $config);

You should set your DI container to provide ConfigManager as a singleton.

Clients

  • Each client can be built using its own Factory class (in their namespace). Factory uses a DI container that should resolve: ClientInterface for HTTP/s communication and ConfigManaer
  • Each client can be configured by ConfigManager.

CacheResponseClient (file)

The CacheResponseClient utilizes PSR-6 (simple-cache) for caching responses, improving development speed by serving cached responses for subsequent requests. Here are some benefits and considerations:

  • Development Efficiency: Speeds up development by caching responses, reducing the need for repeated API calls during development.
  • Local Testing: Enable the saveOnly option in production to cache responses and download them for testing on localhost, ensuring consistency and performance.
  • Customization: Customize cache key preparation by implementing your own contract in CacheKeyMakerAction.php.

CustomizeRequestClient (file)

Alter request before sending it to the HTTPClient. You can throw ClientExceptionInterface. This client could be useful for testing error handling mechanisms in your application and use cached *.shttp file.

use Psr\Http\Message\RequestInterface;
use StrictPhp\HttpClients\Clients\CustomizeRequest\CustomizeRequestConfig;
use StrictPhp\HttpClients\Managers\ConfigManager;

/** @var ConfigManager $configManager */
$configManager->add('www.example.com', new CustomizeRequestConfig(function(RequestInterface $request): RequestInterface {
    return $request->withHeader('uuid', generate_uuid());
}));

CustomResponseClient (file)

Subject to change.

You can define custom response file foe each host.

The #1 parameter in constructor can be:

  • a path on serialized SerializableResponse which created by SaveResponse.php, file with extension shttp it's mean serialized http
  • a path on file with plain text, this is used like body only

EventClient (file)

dependent on PSR-14 (event-dispatcher)

You can attach events before, failed or request success. It is useful for logging.

MainHttpClient (file)

This is first endpoint for debugging. If you use ClientsFactory, this instance will be returned.

MockClient (file)

MockClient use for tests, you define response for current scope.

RetryClient (file)

Retry client is designed to retry failed request with ability to define number of tries and allowlist (based on exception).

SleepClient (file)

The SleepClient allows you to introduce a wait interval between requests, which may be necessary for interacting with external APIs that require rate limiting.

StoreClient (file)

The StoreClient saves request and response, without dependency on PSR-14

Testing

You can save file with extension *.shttp by SaveResponse or use our PSR16 implementation CachePsr16Service. This file you can to use in tests by MockClient.

use StrictPhp\HttpClients\Clients\Mock\MockClient;
/** @var \Psr\Http\Message\RequestInterface $request */
$client = new MockClient(__DIR__ . '/dir/filename.shttp');
$response = $client->sendRequest($request);

$response instanceof \Psr\Http\Message\ResponseInterface;

Write your own client

You can write your own client simply by implementing these interfaces:

  • Client must implement Psr\Http\Client\ClientInterface.
  • Config must implement StrictPhp\HttpClients\Contracts\ConfigInteface
  • Factory for client implement StrictPhp\HttpClients\Contracts\ClientFactoryContract

Below is an example of an implementation:

Config

namespace My;

use StrictPhp\HttpClients\Contracts\ConfigInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use StrictPhp\HttpClients\Entities\AbstractConfig;

/**
 * parameters of constructor must have to filled default values  
 */
class Config extends AbstractConfig 
{
    public function __construct(
        private readonly int $optionA = 1,
        private readonly int $optionB = 2,
    ) {
    }    
}

Client

namespace My;

use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use StrictPhp\HttpClients\Managers\ConfigManager;
use My\Config;

class MyClient implements ClientInterface 
{
    public function __construct(
        private ClientInterface $client,
        private ConfigManager $configManager,
    ) {
    }    


    public function sendRequest(RequestInterface $request): ResponseInterface
    {
        $host = $request->getUri()->getHost();
        $config = $this->configManager->get(Config::class, $host);
        $config->optionA;
        $config->optionB;
        
        // do anything
        $response = $this->client->sendRequest($request)
        // do anything
        
        return $response;
    }
    
}

ClientFactory

namespace My;

use StrictPhp\HttpClients\Contracts\ClientFactoryContract;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use My\Config;

class ClientFactory implements ClientFactoryContract 
{
    public function __construct(
        private ConfigManager $configManager,
    ) {
    } 
    
    public function create(ClientInterface $client): ClientInterface
    {
        return new MyClient($client, $this->configManager);
    }
    
}

strictphp/http-clients 适用场景与选型建议

strictphp/http-clients 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.88k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2024 年 03 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「laravel」 「http-client」 「strictphp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 strictphp/http-clients 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 strictphp/http-clients 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 2.88k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 12
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 2
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-03-08