imcanugur/fly-http 问题修复 & 功能扩展

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

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

imcanugur/fly-http

Composer 安装命令:

composer require imcanugur/fly-http

包简介

PSR-18 compliant, middleware-based HTTP client library for enterprise applications

README 文档

README

A PSR-18 compliant, middleware-based HTTP client library designed for enterprise applications. Built to compete with Guzzle while providing superior architecture for complex HTTP workflows.

Latest Version License PHP Version PSR-18

🎯 Purpose

Fly HTTP Client is not just a "helper for making HTTP requests." It provides a core HTTP traffic management system for enterprise applications.

The library focuses on architectural correctness, maintainability, and extensibility rather than feature bloat.

⚡ Key Features

  • PSR-18 Compliant: Drop-in replacement for any PSR-18 HTTP client
  • Zero Dependencies: Only requires PSR interfaces - no Guzzle, no external libraries
  • Middleware Pipeline: Chain policies for retry, authentication, logging, caching, circuit breaker
  • Transport Abstraction: Switch between native cURL, mock, or custom transports
  • Built-in PSR-7: Complete HTTP message implementation included
  • Enterprise Ready: Circuit breaker, metrics, caching for production systems
  • Immutable Requests: Thread-safe, predictable request handling

🏗️ Architecture Overview

HTTP processing is divided into three distinct layers:

1. Client Layer (Orchestration)

  • Executes the middleware pipeline
  • Delegates to transport for actual HTTP calls
  • Implements PSR-18 ClientInterface
  • Manages business logic flow

2. Middleware Layer (Policy)

  • Applies cross-cutting concerns
  • Can modify requests immutably
  • Observes and logs responses
  • Handles errors and recovery
  • Never makes HTTP calls directly

3. Transport Layer (Execution)

  • Executes actual HTTP requests
  • Can use Guzzle, native curl, or custom implementations
  • Completely abstracted from client logic
  • Enables testing and vendor flexibility

🔗 Middleware System

Middlewares form a processing pipeline:

Request
  ↓
RetryMiddleware    (handles failures)
  ↓
LoggerMiddleware   (logs requests/responses)
  ↓
AuthMiddleware     (adds authentication)
  ↓
Transport          (Guzzle/Native/Custom)
  ↓
Response

Each middleware:

  • Receives a RequestInterface and $next callable
  • Can modify the request immutably
  • Calls $next($request) to continue the pipeline
  • Can observe and process the response

Built-in Middlewares

  • RetryMiddleware: Exponential backoff retry logic
  • LoggerMiddleware: PSR-3 compatible request/response logging
  • AuthMiddleware: Bearer token, Basic auth, custom auth strategies
  • TimeoutMiddleware: Request and connection timeouts

🚀 Basic Usage

use Fly\Http\Client;
use Fly\Http\Transport\NativeCurlTransport;
use Fly\Http\Middleware\RetryMiddleware;
use Fly\Http\Middleware\LoggerMiddleware;

// Create transport (zero dependencies!)
$transport = new NativeCurlTransport();

// Create client
$client = new Client($transport);

// Add middlewares
$client->addMiddleware(new RetryMiddleware(3, 1.0));
$client->addMiddleware(new LoggerMiddleware($logger));

// Make request
$response = $client->sendRequest($request);

⚙️ Advanced Configuration

Circuit Breaker for Fault Tolerance

use Fly\Http\Middleware\CircuitBreakerMiddleware;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

// Create cache for circuit breaker state
$cache = new FilesystemAdapter();

// Add circuit breaker middleware
$client->addMiddleware(new CircuitBreakerMiddleware(
    $cache,
    'api-service',  // Service identifier
    5,              // Failure threshold
    60,             // Recovery timeout (seconds)
    3               // Success threshold for half-open
));

Request Caching

use Fly\Http\Middleware\CacheMiddleware;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

// Create cache for HTTP responses
$cache = new FilesystemAdapter();

// Add caching middleware
$client->addMiddleware(new CacheMiddleware(
    $cache,
    300  // TTL in seconds
));

Metrics & Monitoring

use Fly\Http\Middleware\MetricsMiddleware;

// Add metrics collection
$client->addMiddleware(new MetricsMiddleware($logger, 'api-client'));

// Later, get metrics snapshot
$metrics = $client->getMetrics();
$prometheusOutput = $client->exportMetrics();

Authentication & Timeouts

use Fly\Http\Middleware\AuthMiddleware;
use Fly\Http\Middleware\TimeoutMiddleware;

// Authentication
$client->addMiddleware(new AuthMiddleware('your-token', 'Bearer'));

// Timeouts
$client->addMiddleware(new TimeoutMiddleware(30.0, 10.0));

🧪 Testing

use Fly\Http\Client;
use Fly\Http\Transport\MockTransport;

// Create mock transport for testing
$mockTransport = new MockTransport();
$client = new Client($mockTransport);

// Add predefined responses
$mockTransport->addResponse($successResponse);
$mockTransport->addResponse($errorResponse);

// Or use response factory
$mockTransport->setResponseFactory(function ($request) {
    return new Response(200, [], 'OK');
});

// Test your HTTP logic
$response = $client->sendRequest($request);

// Assert requests were made
$mockTransport->assertRequestMade('GET', 'https://api.example.com/users');

📋 PSR-7 HTTP Messages

Fly includes its own PSR-7 implementation for zero dependencies:

use Fly\Http\Http\RequestFactory;
use Fly\Http\Http\ResponseFactory;
use Fly\Http\Http\StreamFactory;
use Fly\Http\Http\UriFactory;

// Create PSR-17 factories
$requestFactory = new RequestFactory();
$responseFactory = new ResponseFactory();
$streamFactory = new StreamFactory();
$uriFactory = new UriFactory();

// Create messages
$request = $requestFactory->createRequest('GET', 'https://api.example.com');
$response = $responseFactory->createResponse(200);
$stream = $streamFactory->createStream('Hello World');
$uri = $uriFactory->createUri('https://api.example.com');

🚨 Error Handling

use Fly\Http\Exception\CircuitBreakerException;

try {
    $response = $client->sendRequest($request);
} catch (CircuitBreakerException $e) {
    // Circuit breaker is open
    echo "Service unavailable: " . $e->getServiceKey();
} catch (\Psr\Http\Client\ClientExceptionInterface $e) {
    // HTTP client error
    echo "HTTP Error: " . $e->getMessage();
}

🚚 Transport Options

Transport abstraction allows switching implementations:

// Production - Native cURL (recommended)
$client = new Client(new NativeCurlTransport());

// Testing - Mock
$client = new Client(new MockTransport());

// Development - With custom options
$client = new Client(new NativeCurlTransport([
    CURLOPT_TIMEOUT => 60,
    CURLOPT_SSL_VERIFYPEER => false, // Development only!
]));

⚡ Performance Tips

  1. Use NativeCurlTransport for best performance
  2. Enable caching for repeated requests
  3. Configure circuit breakers for resilient systems
  4. Set appropriate timeouts to prevent hanging
  5. Use connection pooling in high-throughput scenarios

📋 PSR Compliance

The library adheres to established PHP standards:

  • PSR-18: HTTP Client interface
  • PSR-7: HTTP Messages (Request/Response)
  • PSR-3: Logger interface
  • PSR-17: HTTP Factories

This ensures compatibility across frameworks and prevents vendor lock-in.

🎯 When to Use

Use Fly HTTP Client when you need:

  • Complex HTTP workflows with multiple policies
  • Enterprise applications requiring audit trails
  • Microservices with circuit breaker patterns
  • Testable HTTP code with transport abstraction
  • Framework agnostic HTTP client

Do not use for:

  • Simple one-off HTTP calls
  • Basic REST API consumption
  • Applications without complex HTTP requirements

📦 Installation

composer require imcanugur/fly-http

🤝 Contributing

We welcome contributions! If you have a feature idea or a bug fix:

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature/YourFeature).
  3. Commit your changes using Conventional Commits.
  4. Push to the branch.
  5. Open a Pull Request.

For bugs and suggestions, please open an issue.

Commit Convention

This project uses Conventional Commits for automatic versioning:

# Feature (minor version bump)
git commit -m "feat: add new middleware"

# Bug fix (patch version bump)
git commit -m "fix: resolve memory leak"

# Breaking change (major version bump)
git commit -m "feat!: remove deprecated API"

Automatic Versioning

GitHub Actions (CI/CD) - Composite Actions

When you push to the main branch, GitHub Actions uses custom composite actions:

# Uses ./.github/actions/version-bump
# Uses ./.github/actions/create-tag
# Uses ./.github/actions/packagist-update

Process:

  1. Version Bump Action: Analyzes conventional commits → determines version bump
  2. Create Tag Action: Updates files, commits changes, creates git tag
  3. Packagist Update Action: Triggers Packagist package update

Using Composite Actions Manually

You can also use the actions in other workflows:

- name: Bump version
  uses: ./.github/actions/version-bump
  with:
    bump_type: auto

- name: Create tag
  uses: ./.github/actions/create-tag
  with:
    version: ${{ steps.bump.outputs.new_version }}

- name: Update Packagist
  uses: ./.github/actions/packagist-update
  with:
    api_token: ${{ secrets.PACKAGIST_API_TOKEN }}
    username: imcanugur

Local Development (CI-Independent)

For local development or other CI systems, use the release script:

# Setup git hooks for automatic release prompts
php bin/setup-hooks

# Manual release commands
php bin/release --auto     # Auto-determine version bump
php bin/release patch      # Manual patch bump (1.0.0 → 1.0.1)
php bin/release minor      # Manual minor bump (1.0.0 → 1.1.0)
php bin/release major      # Manual major bump (1.0.0 → 2.0.0)

# Git hooks will prompt for releases on main branch commits
git add .
git commit -m "feat: add new middleware"
# Hook will ask: "Trigger automatic release?"

Conventional Commits

The system uses Conventional Commits specification:

feat: add new feature          # → minor version bump
fix: resolve bug               # → patch version bump
feat!: breaking change         # → major version bump
docs: update docs             # → no version bump

📄 License

MIT License - see LICENSE file for details.

Enterprise-grade HTTP client built for production systems

imcanugur/fly-http 适用场景与选型建议

imcanugur/fly-http 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 01 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-05