moebius/coroutine

PHP 中的易用协程。

1.0.102 2022-06-22 15:30 UTC

README

真正的“绿色线程”(协程)用于 PHP 8.1。无需插件。协程就像多任务处理,但没有线程带来的许多微妙问题。

兼容性

Moebius 可与其他事件循环协同工作;如果您正在使用 React,Moebius 将运行 React 事件循环;如果您正在使用 Amp,Moebius 将运行 Amp 事件循环。

技巧!要创建兼容事件循环的应用程序,您可以直接针对 moebius/loop 实现进行实现。

必备条件

协程是一个与您的应用程序中其他代码并行运行的函数。您可以像在 React 或 Amp 等框架中使用承诺一样使用协程。实际上,您可以使用大多数基于承诺的库与 Moebius 一起使用。

隐藏承诺

moebius 的主要目的是隐藏承诺的存在;您不需要考虑协程是您应用程序的一部分。您需要考虑协程的唯一情况是您需要并行执行多项操作。

Moebius 允许您的应用程序并行处理多个请求,但您的程序流程无需担心这一点。

协程是承诺

创建协程时,您会得到一个关于未来结果的承诺。您可以通过 then() 方法访问该未来结果,就像您习惯的任何其他承诺对象一样。

<?php
use Moebius\Coroutine as Co;

$coroutine = Co::go(function() {
    Co::sleep(10);
    return true;
});

$coroutine->then(function() {
    echo "Done\n";
});

承诺是协程

<?php
use Moebius\Coroutine as Co;
use GuzzleHttp\Client;

function get(string $url) {
    $client = new Client();
    echo "Connecting to '$url'\n";
    $result = $client->getAsync($url);
    echo "Got response from '$url'\n";
}

$google = Co::go(get(...), 'https://www.google.com');
$bing = Co::go(get(...), 'https://www.bing.com');
$ddg = Co::go(get(...), 'https://www.duckduckgo.com');



## Examples

You can find complete examples in the `examples/` folder. Here is a trivial example
that reads lines from multiple files concurrently: