协程基础组件

Testing Is Documentation

tests/Protocol/CoroutineTest.php协程基础组件 - 图1

协程基础组件主要用于返回当前协程状态以及标识一个服务是否处于协程中,以便于将数据注册到当前协程下面,用于协程上下文。

Uses

  1. <?php
  2. use Leevel\Di\ICoroutine;
  3. use Leevel\Protocol\Coroutine;
  4. use Throwable;

普通服务是否处于协程上下文

  1. public function testCoroutineContext(): void
  2. {
  3. $coroutine = new Coroutine();
  4. $this->assertInstanceOf(ICoroutine::class, $coroutine);
  5. $this->assertFalse($coroutine->context('notFound'));
  6. $coroutine->addContext('notFound');
  7. $this->assertTrue($coroutine->context('notFound'));
  8. }

类是否处于协程上下文

类可以通过添加静态方法 coroutineContext 来自动完成协程上下文标识。

  1. public function testCoroutineContextForClass(): void
  2. {
  3. $coroutine = new Coroutine();
  4. $this->assertFalse($coroutine->context(Demo1::class));
  5. $coroutine->addContext(Demo1::class);
  6. $this->assertTrue($coroutine->context(Demo1::class));
  7. $this->assertTrue($coroutine->context(Demo2::class));
  8. }

当前协程 ID 和父 ID

  1. public function testCoroutineCidAndPcid(): void
  2. {
  3. $coroutine = new Coroutine();
  4. $this->assertSame(-1, $coroutine->cid());
  5. $this->assertFalse($coroutine->pcid());
  6. try {
  7. go(function () use ($coroutine) {
  8. $this->assertSame(1, $coroutine->cid());
  9. $this->assertSame(-1, $coroutine->pcid());
  10. go(function () use ($coroutine) {
  11. $this->assertSame(2, $coroutine->cid());
  12. $this->assertSame(1, $coroutine->pcid());
  13. });
  14. });
  15. } catch (Throwable $th) {
  16. }
  17. }