moebius / coroutine
PHP 中的易用协程。
1.0.102
2022-06-22 15:30 UTC
Requires
- moebius/common: >=1.0
- moebius/loop: >=1.0.100
- moebius/promise: >=1.0.100
Requires (Dev)
- charm/testing: >=1
Suggests
- moebius/async-file: Automatically and transparently makes blocking file system operations non-blocking
- dev-master
- 1.0.102
- 1.0.101
- 1.0.100
- 1.0.11
- 1.0.10
- 1.0.9
- 1.0.8
- 1.0.7
- 1.0.6
- 1.0.5-RC14
- 1.0.5-RC13
- 1.0.5-RC12
- 1.0.5-RC11
- 1.0.5-RC10
- 1.0.5-RC9
- 1.0.5-RC8
- 1.0.5-RC7
- 1.0.5-RC6
- 1.0.5-RC5
- 1.0.5-RC4
- 1.0.5-RC3
- 1.0.5-RC2
- 1.0.5-RC1
- 1.0.5-beta3
- 1.0.5-beta2
- 1.0.5-beta
- 1.0.4-beta
- 1.0.3-beta
- 1.0.2-alpha
- 1.0.1-alpha
- 1.0.0-alpha
- 0.0.10-beta
- 0.0.9-beta
- 0.0.8-beta
- 0.0.7-beta
- 0.0.6-beta
- 0.0.5-beta
- 0.0.4-beta
- 0.0.3-beta
- 0.0.2-beta
- 0.0.1-alpha
This package is auto-updated.
Last update: 2024-08-28 05:35:50 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: