leocavalcante/coroutine-context-api

使用协程上下文作为分层服务定位器和依赖注入容器。

v0.1.0 2021-10-11 18:59 UTC

This package is auto-updated.

Last update: 2024-09-12 02:02:35 UTC


README

使用协程上下文作为分层服务定位器和依赖注入容器。

受以下链接启发 https://reactjs.ac.cn/docs/context.html

安装

composer require leocavalcante/coroutine-context-api

使用方法

提供

\Swoole\Coroutine\Context\provide(string $key, mixed $value): void

根据字符串设置一个值,该值可以从子协程中消费。

use function Swoole\Coroutine\{run, Context\provide};

run(static function(): void {
    provide('message', 'Hello, World!');
});

消费

\Swoole\Coroutine\Context\consume(string $key, [mixed $default]): mixed

从指定的键中消费值。

use function Swoole\Coroutine\{run, Context\provide, Context\consume};

run(static function(): void {
    provide('message', 'Hello, World!');
    go(static fn() => print(consume('message') . PHP_EOL));
});

但是,但是...

这与将参数传递给函数参数有什么不同吗?

consume 函数可以在协程树中查找最近提供的键。

use function Swoole\Coroutine\{run, Context\provide, Context\consume};

run(static function(): void {
    provide('message', 'Hello, World!');
    go(static fn() =>
        go(static fn() =>
            go(static fn() =>
                print(consume('message') . PHP_EOL)
            )
        )
    );
});

这与全局变量有什么不同吗?

这并不是关于全局空间被污染的问题,而是基于父子“协程树”。

run(static function(): void {
    provide('message', 'Hello, World!');
    go(static fn() => print(consume('message') . PHP_EOL));
});

run(static function(): void {
    provide('message', 'Olá, Mundo!');
    go(static fn() => print(consume('message') . PHP_EOL));
});

run(static function(): void {
    go(static fn() => print(consume('message', $default = '你好, 世界!') . PHP_EOL));
});