-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathfiber-local-automatic.php
49 lines (36 loc) · 1.15 KB
/
fiber-local-automatic.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
declare(strict_types=1);
use Revolt\EventLoop;
use Revolt\EventLoop\FiberLocal;
require __DIR__ . '/../vendor/autoload.php';
/**
* This logger uses {@see FiberLocal} to automatically log a transaction identifier bound to the current fiber.
*
* This might be used to log the current URL, authenticated user, or request identifier in an HTTP server.
*/
final class Logger
{
private int $nextId = 1;
private FiberLocal $transactionId;
public function __construct()
{
$this->transactionId = new FiberLocal(fn () => $this->nextId++);
}
public function log(string $message): void
{
echo $this->transactionId->get() . ': ' . $message . PHP_EOL;
}
}
$logger = new Logger();
EventLoop::delay(1, static function () use ($logger) {
$logger->log('Initializing...');
$suspension = EventLoop::getSuspension();
EventLoop::delay(1, static fn () => $suspension->resume());
$suspension->suspend();
$logger->log('Done.');
});
$logger->log('Initializing...');
$suspension = EventLoop::getSuspension();
EventLoop::delay(3, static fn () => $suspension->resume());
$suspension->suspend();
$logger->log('Done.');