Mix PHP V2 生態:讓 Guzzle 支持 Swoole 的 Hook 協程

Guzzle 是一個很是流行的 PHP 的 HTTP 客戶端,如今各大廠的 SDK 也都開始基於 Guzzle 開發,由於 Swoole 只支持 PHP Stream 的協程 Hook ,而 Guzzle 默認是使用 cURL 擴展的,因此 Mix PHP 開發了 Guzzle Hook,能在不修改源碼的狀況下讓 Guzzle 協程化。php

Github

安裝

使用 Composer 安裝:html

composer require mix/guzzle-hook

在項目的 composer.json 文件中增長 extra 配置項,以下:git

"extra": {
    "include_files": [
      "vendor/mix/guzzle-hook/src/functions_include.php"
    ]
}

使用

直接使用 Guzzle 開發

無需作任何特殊的代碼處理,直接根據 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();

});

第三方 SDK 依賴 Guzzle

好比: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;
    }

});
相關文章
相關標籤/搜索