|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
use Amp\Delayed; |
|
4
|
|
|
use PHPinnacle\Ensign\Dispatcher; |
|
5
|
|
|
use PHPinnacle\Ensign\Processor; |
|
6
|
|
|
|
|
7
|
|
|
require __DIR__ . '/../vendor/autoload.php'; |
|
8
|
|
|
|
|
9
|
|
|
class Publish |
|
10
|
|
|
{ |
|
11
|
|
|
public $signal; |
|
12
|
|
|
public $arguments; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(string $signal, ...$arguments) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->signal = $signal; |
|
17
|
|
|
$this->arguments = $arguments; |
|
18
|
|
|
} |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
class Publisher |
|
22
|
|
|
{ |
|
23
|
|
|
private $processor; |
|
24
|
|
|
private $listeners = []; |
|
25
|
|
|
|
|
26
|
|
|
public function __construct(Processor $processor) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->processor = $processor; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function listen(string $signal, callable $listener): self |
|
32
|
|
|
{ |
|
33
|
|
|
$this->listeners[$signal][] = $listener; |
|
34
|
|
|
|
|
35
|
|
|
return $this; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function __invoke(Publish $message) |
|
39
|
|
|
{ |
|
40
|
|
|
$listeners = $this->listeners[$message->signal] ?? []; |
|
41
|
|
|
|
|
42
|
|
|
yield \array_map(function ($listener) use ($message) { |
|
43
|
|
|
return $this->processor->execute($listener, $message->arguments); |
|
44
|
|
|
}, $listeners); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
Amp\Loop::run(function () { |
|
49
|
|
|
$processor = new Processor(); |
|
50
|
|
|
|
|
51
|
|
|
$publisher = new Publisher($processor); |
|
52
|
|
|
$publisher |
|
53
|
|
|
->listen('print', function ($num) { |
|
54
|
|
|
for ($i = 0; $i < $num; $i++) { |
|
55
|
|
|
echo '-'; |
|
56
|
|
|
|
|
57
|
|
|
yield new Delayed(100); |
|
58
|
|
|
} |
|
59
|
|
|
}) |
|
60
|
|
|
->listen('print', function ($num) { |
|
61
|
|
|
for ($i = 0; $i < $num; $i++) { |
|
62
|
|
|
echo '+'; |
|
63
|
|
|
|
|
64
|
|
|
yield new Delayed(100); |
|
65
|
|
|
} |
|
66
|
|
|
}) |
|
67
|
|
|
->listen('print', function ($num) { |
|
68
|
|
|
for ($i = 0; $i < $num; $i++) { |
|
69
|
|
|
echo '*'; |
|
70
|
|
|
|
|
71
|
|
|
yield new Delayed(50); |
|
72
|
|
|
} |
|
73
|
|
|
}) |
|
74
|
|
|
; |
|
75
|
|
|
|
|
76
|
|
|
$dispatcher = new Dispatcher($processor); |
|
77
|
|
|
$dispatcher |
|
78
|
|
|
->register(Publish::class, $publisher) |
|
79
|
|
|
; |
|
80
|
|
|
|
|
81
|
|
|
yield $dispatcher->dispatch(new Publish('print', 10)); |
|
82
|
|
|
}); |
|
83
|
|
|
|