rx/http

RxPHP 的 Http 客户端

2.1.3 2022-09-25 21:23 UTC

This package is auto-updated.

Last update: 2024-08-26 01:38:00 UTC


README

这个库是 RxPHP 对 ReactPHP 的 Http-client 库的包装。它允许您进行异步 HTTP 调用并通过 RxPHP 可观察对象发出结果。

它使用 Voryx 事件循环,其行为类似于 JavaScript 事件循环。也就是说,您不需要启动它。

##安装

使用 composer 安装依赖项

  $ php composer.phar require "rx/http"      

使用方法

获取

    
$source = \Rx\React\Http::get('https://www.example.com/');

$source->subscribe(
    function ($data) {
        echo $data, PHP_EOL;
    },
    function (\Exception $e) {
        echo $e->getMessage(), PHP_EOL;
    },
    function () {
        echo "completed", PHP_EOL;
    }
);
    

提交

    
$postData = json_encode(["test" => "data"]);
$headers  = ['Content-Type' => 'application/json'];

$source = \Rx\React\Http::post('https://www.example.com/', $postData, $headers);

$source->subscribe(
    function ($data) {
        echo $data, PHP_EOL;
    },
    function (\Exception $e) {
        echo $e->getMessage(), PHP_EOL;
    },
    function () {
        echo "completed", PHP_EOL;
    }
);
    

多个异步请求

$imageTypes = ["png", "jpeg", "webp"];

$images = \Rx\Observable::fromArray($imageTypes)
    ->flatMap(function ($type) {
        return \Rx\React\Http::get("http://httpbin.org/image/{$type}")->map(function ($image) use ($type) {
            return [$type => $image];
        });
    });

$images->subscribe(
    function ($data) {
        echo "Got Image: ", array_keys($data)[0], PHP_EOL;
    },
    function (\Exception $e) {
        echo $e->getMessage(), PHP_EOL;
    },
    function () {
        echo "completed", PHP_EOL;
    }
);

更多详细信息,请参阅 示例