Docs 菜单
Docs 主页
/ / /
PHP 库手册
/ /

MongoDB\Client::addSubscriber()

在此页面上

  • 定义
  • 参数
  • 错误/异常
  • 行为
  • 例子
  • 另请参阅

1.18版本新增

MongoDB\Client::addSubscriber()

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

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

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

MongoDB\Driver\Exception\InvalidArgumentException 如果订阅者是 MongoDB\Driver\Monitoring\LogSubscriber ,因为记录器只能在全局范围内注册到 MongoDB\Driver\Monitoring\addSubscriber。

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

创建 MongoDB\Driver\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}

后退

__get()