ahmard/guzwrap

流行的 PHP HTTP 客户端 "GuzzleHttp" 的包装器

2.4.4 2022-12-21 15:21 UTC

README

Guzwrap 是围绕 GuzzleHttp 的面向对象的包装器。
此项目旨在使使用 Guzzle 发送请求变得更加容易和愉快。

支持的 PHP 版本

Guzwrap 需要 PHP >= 7.4 或 >= 8.0

安装

请确保您已安装 Composer

composer require ahmard/guzwrap

使用方法

use Guzwrap\Request;

//simple request
$result = Request::get('https://:8002')->exec();

//with authentication
Request::get('https://:8002')
    ->auth('username', 'password')
    ->exec();
  • 获取 Guzwrap 实例
use Guzwrap\Request;

$instance = Request::create();
//Do something...
  • 带有 cookies 的请求
use Guzwrap\Request;

Request::create()->get('https://:8002')
    ->withCookie()
    //or use cookie file
    ->withCookieFile('path/to/file')
    //use cookie session
    ->withCookieSession('session_name')
    //use array too
    ->withCookieArray([
        'first_name' => 'Jane',
        'other_names' => 'Doe'
    ], 'localhost')
    //Use single cookie across requests
    ->withSharedCookie();
  • 处理重定向
use Guzwrap\Request;
use Guzwrap\Wrapper\Redirect;

Request::get('https://:8002')
    ->redirects(function(Redirect $redirect){
        $redirect->max(5);
        $redirect->strict();
        $redirect->referer('http://goo.gl');
        $redirect->protocols('http');
        $redirect->trackRedirects();
        $redirect->onRedirect(function(){
            echo "Redirection detected!";
        });
    })->exec();
  • 头部
use Guzwrap\Request;
use Guzwrap\Wrapper\Header;

Request::get('https://:8002')
    ->header(function(Header $header){
        $header->add('hello', 'world');
        $header->add('planet', 'earth');
    })
    ->exec();
  • 查询
use Guzwrap\Request;

Request::get('https://google.com')
    ->query('q', 'Who is jane doe')
    ->exec();
  • POST 表单数据
use Guzwrap\Request;
use Guzwrap\Wrapper\Form;

Request::uri('https://:8002')
    ->post(function(Form $form){
        $form->field('first_name', 'Jane');
        $form->field('last_name', 'Doe');
    })
    ->exec();

//Post with multipart data
Request::uri('https://:8002')
  ->post(function(Form $form){
      $form->method('post');
      $form->field('full_name', 'Jane Doe');
      $form->file('avatar', 'C:\jane_doe.jpg');
  })->exec();

您可以使用 RequestInterface::form() 方法

注意: 如果您没有将表单方法设置为 POST,则所有输入字段都将被视为 URL 查询。

use Guzwrap\Request;
use Guzwrap\Wrapper\Form;
use Guzwrap\Wrapper\File;

Request::form(function (Form $form){
    $form->method('get'); //You can use any http method here
    $form->action('localhost:8002');
    $form->field('name', 'Guzwrap');
})->exec();

//Send file with custom information
Request::form(function(Form $form){
    $form->method('post');
    $form->action('https://:8002');
    $form->field('full_name', 'Jane Doe');
    $form->file(function(File $file){
        $file->field('avatar');
        $file->path('C:\jane_doe.jpg');
        $file->name('John_doe.gif');
    });
})->exec();

更多 请求 使用

  • 使用请求数据
use Guzwrap\Request;
use Guzwrap\UserAgent;

//Basic usage
$request = Request::query('artist', 'Taylor Swift')
    ->useData([
        'headers' => [
            'pass' => 'my-random-pass',
            'user-agent' => 'My Custom Useragent',
        ],
        'query' => [
            'action' => 'create'
        ]       
    ])->exec();

//User other request's data
$request1 = Request::userAgent(UserAgent::FIREFOX)
    ->query([
        'username' => 'Ahmard',
        'realm' => 'admin'
    ]);

$realRequest = Request::useData($request1->getData());
  • 使用请求对象
use Guzwrap\Request;
use Guzwrap\UserAgent;

$request1 = Request::query('username', 'Ahmard');

$request2 = Request::query('language', 'PHP')
    ->userAgent(UserAgent::CHROME)
    ->allowRedirects(false);

$realRequest = Request::useRequest($request1, $request2); //Has request 1 and request 2 data

异步操作

use Guzwrap\Request;
use Psr\Http\Message\ResponseInterface;

$promise = Request::get('localhost:8002')
    ->query('wraps', 'guzzlehttp')
    ->query('name', 'guzwrap')
    ->execAsync();

$promise->then(function (ResponseInterface $response){
    var_dump($response->getBody()->getContents());
});

$promise->wait();
  • 同时运行多个请求

    php -S localhost:8002 index.php
    • 创建一个 index.php 文件并将以下代码放入其中
    \sleep($_GET['sleep']);
    echo $_GET['sleep'];
    • 创建 test.php 文件并将以下代码放入其中
    use Guzwrap\Request;
    use Psr\Http\Message\ResponseInterface;
    
    $promise = Request::get('localhost:8002')
        ->query('wraps', 'guzzlehttp')
        ->query('sleep', 2)
        ->execAsync();
    
    $promise->then(function (ResponseInterface $response){
        var_dump($response->getBody()->getContents());
    });
    
    $promise2 = Request::get('localhost:8002')
        ->query('name', 'guzwrap')
        ->query('sleep', 1)
        ->execAsync();
    
    $promise2->then(function (ResponseInterface $response){
        var_dump($response->getBody()->getContents());
    });
    
    $promise->wait();
    $promise2->wait();
    • 现在运行 test.php 文件
    php test.php
  • 使用 Concurrent 类来管理 Guzzle 请求并发

    use Guzwrap\Request;  
    
    $promise1 = Request::get('localhost:8002')->execAsync();
    $promise2 = Request::get('localhost:8002')->execAsync();
    
    $responses = Request::concurrent($promise1, $promise2)->unwrap();
    
    echo $responses[0]->getStatusCode() . PHP_EOL;
    echo $responses[1]->getReasonPhrase() . PHP_EOL;
  • 使用请求池
    use Guzwrap\Request;
    use Guzwrap\Wrapper\Pool;
    use GuzzleHttp\Exception\RequestException;
    use GuzzleHttp\Psr7\Response;
    use Psr\Http\Message\ResponseInterface;
    
    require 'vendor/autoload.php';
    
    $pool = Request::pool(function (Pool $pool) {
        $pool->concurrency(5);
        $pool->fulfilled(function (Response $response, $index) {
            // this is delivered each successful response
        });
        $pool->rejected(function (RequestException $reason, $index) {
            // this is delivered each failed request
        });
    
        $pool->requests(function ($total) {
            $uri = 'http://127.0.0.1:8002';
            for ($i = 0; $i < $total; $i++) {
                yield new \GuzzleHttp\Psr7\Request('GET', $uri);
            }
        });
    });
    
    $promise = $pool->promise();
    
    $promise->then(function (ResponseInterface $response){
        echo "{$response->getStatusCode()} @ {$response->getReasonPhrase()}\n";
    });
    
    $promise->wait();

UserAgent

我们提供自定义用户代理,以帮助轻松发送请求。

use Guzwrap\Request;
use Guzwrap\UserAgent;

Request::userAgent(UserAgent::CHROME);

//Choose specific useragent index from array
Request::userAgent(UserAgent::CHROME, '1');

//Choose sub-useragent
Request::userAgent(UserAgent::CHROME, '9.1');
  • 列出用户代理
use Guzwrap\UserAgent;

$userAgents = UserAgent::init()->getAvailable();
  • 获取随机用户代理
use Guzwrap\UserAgent;

$randomUA = UserAgent::init()->getRandom();
  • 将用户代理添加到集合中。
    请参阅用户代理 定义示例
use Guzwrap\UserAgent;

UserAgent::init()->addFile('/path/to/user-agents.json');
  • 使用原始用户代理
    请注意,您只能将 Guzwrap\UserAgent 类传递给请求对象,不能再传递其他任何内容。
    这可能会为未来的其他可能性打开大门。
use Guzwrap\UserAgent;
use Guzwrap\Request;

$request = Request::userAgent(UserAgent::raw('Browser 1.0 (Windows NT 10.0; Win64; x64)'));

操作 Guzzle StackHandler

use Guzwrap\Request;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;

Request::stack(function (HandlerStack $stack){
    $stack->setHandler(new CurlHandler());
    //Do something here
});

中间件

向 GuzzleHttp 请求添加 中间件

use Guzwrap\Request;
use Psr\Http\Message\RequestInterface;

/**
 * An example of middleware that add header to requests
 * @link https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html
 */
Request::middleware(function(){
    return function (callable $handler){
        return function (
            RequestInterface $request,
            array $options
        ) use ($handler){
            $request = $request->withHeader('X-Guzwrap-Version', 'V2');
            return $handler($request, $options);
        };
    };
});

扩展 Guzwrap

use Guzwrap\Wrapper\Guzzle;
use Psr\Http\Message\ResponseInterface;

require 'vendor/autoload.php';

class Client extends Guzzle
{
    public static function create(): Client
    {
        return new Client();
    }

    public function boom(): ResponseInterface
    {
        echo "Executing request...\n";
        return parent::exec();
    }
}

$client = Client::create()
    ->get('localhost:8002')
    ->withCookie()
    ->boom();

测试

在运行测试之前,使用 Rust PHP 内置服务器

php -S localhost:8002 -t tests/raw/

运行测试

composer test

享受 😎