fofx/guzzle-middleware 问题修复 & 功能扩展

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

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

fofx/guzzle-middleware

Composer 安装命令:

composer require fofx/guzzle-middleware

包简介

Enhanced Guzzle client with middleware, debugging, and proxy support.

README 文档

README

Latest Version on Packagist Total Downloads License

FOfX Guzzle Middleware is an enhanced Guzzle client with middleware, debugging, and proxy support. It provides extended functionality for capturing detailed request and response information, making it easier to debug and log HTTP transactions in your PHP applications.

Features

  • Enhanced Guzzle client with middleware support
  • Detailed request and response logging
  • Debug information capture
  • Proxy configuration support
  • Easy-to-use interface for making HTTP requests
  • Flexible configuration options

Requirements

  • PHP 8.1 or higher
  • Guzzle 7.9 or higher

Installation

You can install the package via Composer:

composer require fofx/guzzle-middleware

Development Server

The package includes a development server for testing and development. Start it before running tests:

php -S localhost:8000 public/dev-server.php

The dev server provides endpoints for testing:

  • /redirect/{n} - Redirects n times
  • /error/{code} - Returns specified HTTP error code
  • /delay/{seconds} - Delays response
  • /api/test - Basic test endpoint
  • /api/echo - Echoes request details

Note: The dev server must be running for unit tests to pass.

Usage

Basic Usage

Here's a simple example of how to use the MiddlewareClient:

require __DIR__ . '/vendor/autoload.php';

use FOfX\GuzzleMiddleware\MiddlewareClient;

$client = new MiddlewareClient();
$response = $client->makeRequest('GET', 'http://httpbin.org/redirect/2');
print_r($client->getAllTransactions());

This should print each transaction in the redirect chain:

Array
(
    [0] => Array
        (
            [request] => Array
                (
                    [method] => GET
                    [url] => http://httpbin.org/redirect/2
                    [headers] => {"User-Agent":["GuzzleHttp\/7"],"Host":["httpbin.org"]}
                    [body] => 
                    [protocol] => 1.1
                    [target] => /redirect/2
                )

            [response] => Array
                (
                    [statusCode] => 302
                    [headers] => {"Date":["Mon, 13 Jan 2025 19:03:26 GMT"],"Content-Type":["text\/html; charset=utf-8"],"Content-Length":["247"],"Connection":["keep-alive"],"Server":["gunicorn\/19.9.0"],"Location":["\/relative-redirect\/1"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Credentials":["true"]}
                    [body] => <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="/relative-redirect/1">/relative-redirect/1</a>.  If not click the link.
                    [contentLength] => 247
                    [reasonPhrase] => FOUND
                )

        )

    [1] => Array
        (
            [request] => Array
                (
                    [method] => GET
                    [url] => http://httpbin.org/relative-redirect/1
                    [headers] => {"Host":["httpbin.org"],"User-Agent":["GuzzleHttp\/7"]}
                    [body] => 
                    [protocol] => 1.1
                    [target] => /relative-redirect/1
                )

            [response] => Array
                (
                    [statusCode] => 302
                    [headers] => {"Date":["Mon, 13 Jan 2025 19:03:28 GMT"],"Content-Type":["text\/html; charset=utf-8"],"Content-Length":["0"],"Connection":["keep-alive"],"Server":["gunicorn\/19.9.0"],"Location":["\/get"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Credentials":["true"]}
                    [body] => 
                    [contentLength] => 0
                    [reasonPhrase] => FOUND
                )

        )

    [2] => Array
        (
            [request] => Array
                (
                    [method] => GET
                    [url] => http://httpbin.org/get
                    [headers] => {"Host":["httpbin.org"],"User-Agent":["GuzzleHttp\/7"]}
                    [body] => 
                    [protocol] => 1.1
                    [target] => /get
                )

            [response] => Array
                (
                    [statusCode] => 200
                    [headers] => {"Date":["Mon, 13 Jan 2025 19:03:30 GMT"],"Content-Type":["application\/json"],"Content-Length":["233"],"Connection":["keep-alive"],"Server":["gunicorn\/19.9.0"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Credentials":["true"]}
                    [body] => {
  "args": {}, 
  "headers": {
    "Host": "httpbin.org", 
    "User-Agent": "GuzzleHttp/7", 
    "X-Amzn-Trace-Id": "Root=1-67856380-2722bf0639f803eb79d6fd4b"
  }, 
  "origin": "IP REMOVED", 
  "url": "http://httpbin.org/get"
}

                    [contentLength] => 233
                    [reasonPhrase] => OK
                )

        )

)

To print just the last transaction, use the getLastTransaction method:

print_r($client->getLastTransaction());

This should print the last transaction.

Note: The elements are named 'request' and 'response' instead of '0', '1', etc.

Array
(
    [request] => Array
        (
            [method] => GET
            [url] => http://httpbin.org/get
            [headers] => {"Host":["httpbin.org"],"User-Agent":["GuzzleHttp\/7"]}
            [body] => 
            [protocol] => 1.1
            [target] => /get
        )

    [response] => Array
        (
            [statusCode] => 200
            [headers] => {"Date":["Mon, 13 Jan 2025 19:03:30 GMT"],"Content-Type":["application\/json"],"Content-Length":["233"],"Connection":["keep-alive"],"Server":["gunicorn\/19.9.0"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Credentials":["true"]}
            [body] => {
  "args": {}, 
  "headers": {
    "Host": "httpbin.org", 
    "User-Agent": "GuzzleHttp/7", 
    "X-Amzn-Trace-Id": "Root=1-67856380-2722bf0639f803eb79d6fd4b"
  }, 
  "origin": "IP REMOVED", 
  "url": "http://httpbin.org/get"
}

            [contentLength] => 233
            [reasonPhrase] => OK
        )

)

To print a summary of the transactions, use the getTransactionSummary method:

print_r($client->getTransactionSummary());

This should print a summary of the transactions:

Array
(
    [request_methods] => Array
        (
            [0] => GET
            [1] => GET
            [2] => GET
        )

    [request_urls] => Array
        (
            [0] => http://httpbin.org/redirect/2
            [1] => http://httpbin.org/relative-redirect/1
            [2] => http://httpbin.org/get
        )

    [request_protocols] => Array
        (
            [0] => 1.1
            [1] => 1.1
            [2] => 1.1
        )

    [request_targets] => Array
        (
            [0] => /redirect/2
            [1] => /relative-redirect/1
            [2] => /get
        )

    [response_status_codes] => Array
        (
            [0] => 302
            [1] => 302
            [2] => 200
        )

    [response_content_lengths] => Array
        (
            [0] => 247
            [1] => 0
            [2] => 233
        )

    [response_reason_phrases] => Array
        (
            [0] => FOUND
            [1] => FOUND
            [2] => OK
        )

)

To print the Guzzle debug stream, use the getDebug method:

print_r($client->getDebug());

This should print the following:

Array
(
    [http://httpbin.org/redirect/2] => * Found bundle for host: 0x1ef4ffa2960 [serially]
* Re-using existing connection with host httpbin.org
> GET /get HTTP/1.1
Host: httpbin.org
User-Agent: GuzzleHttp/7

* Request completely sent off
< HTTP/1.1 200 OK
< Date: Mon, 13 Jan 2025 19:03:30 GMT
< Content-Type: application/json
< Content-Length: 233
< Connection: keep-alive
< Server: gunicorn/19.9.0
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Credentials: true
< 
* Connection #0 to host httpbin.org left intact
nection #0 to host httpbin.org left intact
edentials: true
< 
* Connection #0 to host httpbin.org left intact

)

POST Example

To get the last transaction for a POST request, use the makeRequest method with the POST method:

$client = new MiddlewareClient();
$response = $client->makeRequest('POST', 'http://localhost:8000/api/post', [
    'form_params' => ['username' => 'testuser', 'password' => 'secret123']
]);
print_r($client->getLastTransaction());

Using the makeMiddlewareRequest Function

Alternatively, you can use the makeMiddlewareRequest function for an alternative approach. See examples/makeMiddlewareRequest.php.

require __DIR__ . '/../vendor/autoload.php';

use FOfX\GuzzleMiddleware;
use FOfX\GuzzleMiddleware\MiddlewareClient;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Level;

// Create Monolog logger with stdout handler
$logger = new Logger('guzzle-middleware');
$logger->pushHandler(new StreamHandler('php://stdout', Level::Info));

// Create a new MiddlewareClient instance with logger
$client = new MiddlewareClient([], $logger);

$config = [];
$options = [];
$rotateUserAgent = false;

// Make a request to local dev server
$result = GuzzleMiddleware\makeMiddlewareRequest('GET', 'http://httpbin.org/redirect/2', $config, $options, $logger, $rotateUserAgent);
print_r($result);

Documentation

Detailed documentation can be found in the docs folder:

  • Example Outputs - Shows sample outputs from key methods like getAllTransactions(), getLastTransaction(), getTransactionSummary(), and getDebug() when handling redirect chains
  • Middleware Algorithm - Explains the algorithm used to handle redirects and other middleware
  • Middleware Flow - A sequence diagram showing the flow of the MiddlewareClient
  • Middleware Structure - A Mermaid markdown diagram showing the structure of the MiddlewareClient

Configuration Options

The MiddlewareClient constructor accepts the following parameters:

  • $config (array): Guzzle configuration options
  • $logger (LoggerInterface): A PSR-3 compatible logger
  • $proxyConfig (array): Proxy configuration options

Proxy Configuration

To use a proxy with the MiddlewareClient:

$proxyConfig = ['proxy' => 'http://proxy.example.com:8000'];
$client = new MiddlewareClient(proxyConfig: $proxyConfig);

Testing and Development

Remember to start the development server before running tests.

To run the PHPUnit test suite through composer:

composer test

To use PHPStan for static analysis:

composer phpstan

To use PHP-CS-Fixer for code style:

composer cs-fix

License

The MIT License (MIT). Please see License File for more information.

Credits

This package is built on top of Guzzle, a PHP HTTP client library.

fofx/guzzle-middleware 适用场景与选型建议

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

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

围绕 fofx/guzzle-middleware 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-09-21