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.
🎯 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
RequestInterfaceand$nextcallable - 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
- Use NativeCurlTransport for best performance
- Enable caching for repeated requests
- Configure circuit breakers for resilient systems
- Set appropriate timeouts to prevent hanging
- 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:
- Fork the repository.
- Create a new branch (
git checkout -b feature/YourFeature). - Commit your changes using Conventional Commits.
- Push to the branch.
- 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:
- Version Bump Action: Analyzes conventional commits → determines version bump
- Create Tag Action: Updates files, commits changes, creates git tag
- 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
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 3
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-05