对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

MongoDB\Client::addSubscriber()

1.18版本新增。

MongoDB\Client::addSubscriber()

向此客户端注册监控事件订阅者。 订阅者将收到有关该客户端的所有事件的通知。

function addSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber): void
$subscriber : MongoDB\驱动程序\监控\Subscriber
向此客户端注册的监控事件订阅者。

MongoDB\Exception\InvalidArgumentException 用于与参数或选项解析相关的错误。

MongoDB\ 驱动程序\Exception\InvalidArgumentException 如果订阅者是 MongoDB\ 驱动程序\Monitoring\LogSubscriber ,因为记录器只能在 MongoDB\ 驱动程序\Monitoring\addSubscriber 全局注册。

如果$subscriber已向此客户端注册,则此函数为空操作。 如果$subscriber也已在全局注册,则该客户端的每个事件仍只会收到一次通知。

创建用于记录所有事件的MongoDB\ 驱动程序\Monitoring\CommandSubscriber:

<?php use MongoDB\Driver\Monitoring\CommandSubscriber;use MongoDB\Driver\Monitoring\CommandStartedEvent;use MongoDB\Driver\Monitoring\CommandSucceededEvent;use MongoDB\Driver\Monitoring\CommandFailedEvent; class LogCommandSubscriber implements CommandSubscriber{ private $stream; public function __construct($stream) { $this->stream = $stream; } public function commandStarted(CommandStartedEvent $event): void { fwrite($this->stream, sprintf( 'Started command #%d "%s": %s%s', $event->getRequestId(), $event->getCommandName(), Document::fromPHP($event->getCommand())->toCanonicalExtendedJSON(), PHP_EOL, )); } public function commandSucceeded(CommandSucceededEvent $event): void { fwrite($this->stream, sprintf( 'Succeeded command #%d "%s" in %d microseconds: %s%s', $event->getRequestId(), $event->getCommandName(), $event->getDurationMicros(), json_encode($event->getReply()), PHP_EOL, )); } public function commandFailed(CommandFailedEvent $event): void { fwrite($this->stream, sprintf( 'Failed command #%d "%s" in %d microseconds: %s%s', $event->getRequestId(), $event->getCommandName(), $event->getDurationMicros(), $event->getError()->getMessage(), PHP_EOL, )); }}

然后,订阅者可以在客户端注册:

<?php $client = new MongoDB\Client();$subscriber = new LogCommandSubscriber(STDERR); $client->addSubscriber($subscriber); $client->test->users->insertOne(['username' => 'alice']);

上述代码会将以下内容写入stderr 输出:

Started command #1 "insert": { "insert" : "users", "ordered" : true, "$db" : "test", "lsid" : { "id" : { "$binary" : { "base64" : "dKTBhZD7Qvi0vUhvR58mCA==", "subType" : "04" } } }, "documents" : [ { "username" : "alice", "_id" : { "$oid" : "655d1fca12e81018340a4fc2" } } ] }Succeeded command #1 "insert" in 876 microseconds: {"n":1,"ok":1}