Guzzle 是一个很是流行的 PHP 的 HTTP 客户端,如今各大厂的 SDK 也都开始基于 Guzzle 开发,由于 Swoole 只支持 PHP Stream 的协程 Hook ,而 Guzzle 默认是使用 cURL 扩展的,因此 Mix PHP 开发了 Guzzle Hook,能在不修改源码的状况下让 Guzzle 协程化。php
使用 Composer 安装:html
composer require mix/guzzle-hook
在项目的 composer.json
文件中增长 extra
配置项,以下:git
"extra": { "include_files": [ "vendor/mix/guzzle-hook/src/functions_include.php" ] }
无需作任何特殊的代码处理,直接根据 Guzzle 文档使用:github
// Mix PHP 中是 xgo ,原生 swoole 是 go go(function () { $client = new GuzzleHttp\Client(); $res = $client->request('GET', 'https://api.github.com/user', [ 'auth' => ['user', 'pass'], ]); echo $res->getStatusCode(); });
好比:json
这类第三方库从 composer.json 的 require 能看出来依赖了 guzzlehttp/guzzle,则能够在 Swoole 的协程中直接使用。api
// Mix PHP 中是 xgo ,原生 swoole 是 go go(function () { try { // 实例化一个证书对象,入参须要传入腾讯云帐户secretId,secretKey $cred = new Credential("secretId", "secretKey"); // # 实例化要请求产品(以cvm为例)的client对象 $client = new CvmClient($cred, "ap-guangzhou"); // 实例化一个请求对象 $req = new DescribeZonesRequest(); // 经过client对象调用想要访问的接口,须要传入请求对象 $resp = $client->DescribeZones($req); print_r($resp->toJsonString()); } catch (TencentCloudSDKException $e) { echo $e; } });