|
2 | 2 |
|
3 | 3 | require __DIR__ . '/vendor/autoload.php'; |
4 | 4 |
|
5 | | -// start-mysubscriber |
6 | | -class MySubscriber implements MongoDB\Driver\Monitoring\SDAMSubscriber |
| 5 | +// start-command-subscriber |
| 6 | +class MyCommandSubscriber implements MongoDB\Driver\Monitoring\CommandSubscriber |
7 | 7 | { |
8 | | - /** @param resource $stream */ |
9 | | - public function __construct(private $stream) |
| 8 | + public function __construct(private $stream) {} |
| 9 | + |
| 10 | + public function commandStarted(MongoDB\Driver\Monitoring\CommandStartedEvent $event): void |
10 | 11 | { |
| 12 | + fwrite($this->stream, sprintf( |
| 13 | + 'Started command #%d "%s": %s%s', |
| 14 | + $event->getRequestId(), |
| 15 | + $event->getCommandName(), |
| 16 | + MongoDB\BSON\Document::fromPHP($event->getCommand())->toCanonicalExtendedJSON(), |
| 17 | + PHP_EOL, |
| 18 | + )); |
11 | 19 | } |
12 | 20 |
|
13 | | - public function serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent $event): void |
14 | | - { |
| 21 | + public function commandSucceeded(MongoDB\Driver\Monitoring\CommandSucceededEvent $event): void {} |
| 22 | + public function commandFailed(MongoDB\Driver\Monitoring\CommandFailedEvent $event): void {} |
| 23 | +} |
| 24 | +// end-command-subscriber |
| 25 | + |
| 26 | +// start-sdam-subscriber |
| 27 | +class MySDAMSubscriber implements MongoDB\Driver\Monitoring\SDAMSubscriber |
| 28 | +{ |
| 29 | + public function __construct(private $stream) {} |
| 30 | + |
| 31 | + public function serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent $event): void { |
15 | 32 | fprintf( |
16 | 33 | $this->stream, |
17 | 34 | 'Server opening on %s:%s\n', |
18 | 35 | $event->getHost(), |
19 | 36 | $event->getPort(), |
| 37 | + PHP_EOL, |
20 | 38 | ); |
21 | 39 | } |
22 | 40 |
|
@@ -52,20 +70,23 @@ public function topologyOpening(MongoDB\Driver\Monitoring\TopologyOpeningEvent $ |
52 | 70 | { |
53 | 71 | } |
54 | 72 | } |
55 | | -// end-mysubscriber |
| 73 | +// end-sdam-subscriber |
56 | 74 |
|
57 | 75 | $uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your connection URI'); |
58 | 76 | $client = new MongoDB\Client($uri); |
59 | 77 |
|
60 | 78 | $collection = $client->db->my_coll; |
61 | 79 |
|
62 | | -// start-add-sub |
63 | | -$subscriber = new MySubscriber(STDERR); |
64 | | -$client->addSubscriber($subscriber); |
65 | | -// end-add-sub |
| 80 | +// start-add-subs |
| 81 | +$commandSub = new MyCommandSubscriber(STDERR); |
| 82 | +$sdamSub = new MySDAMSubscriber(STDERR); |
| 83 | + |
| 84 | +$client->addSubscriber($commandSub); |
| 85 | +$client->addSubscriber($sdamSub); |
| 86 | +// end-add-subs |
66 | 87 |
|
67 | 88 | $collection->insertOne(['x' => 100]); |
68 | 89 |
|
69 | 90 | // start-remove-sub |
70 | | -$client->removeSubscriber($subscriber); |
| 91 | +$client->removeSubscriber($commandSub); |
71 | 92 | // end-remove-sub |
0 commit comments