pccomponentes/mongodb-transaction

v1.0.2 2020-07-23 14:01 UTC

This package is auto-updated.

Last update: 2024-09-23 22:37:03 UTC


README

问题

在 MongoDB 中使用事务的方式与典型的关系型数据库连接(MySQL、PostgreSQL 等)不同。

在 MongoDB 中,会生成一个会话,并且所有操作都必须与该 会话 关联。

这意味着对于代码中任何地方的任何写操作,你都必须将 与事务关联的会话 发送到 MongoDB。

解决方案

已经扩展了 ClientCollectionDatabase 类。可以生成一个会话并将其传递给每个类,从开始就控制事务。

用法

不要实例化原始的 \MongoDB\Client,而是实例化 PcComponentes\Transaction\Driver\MongoDB\Client 类。

<?php

$client = new PcComponentes\Transaction\Driver\MongoDB\Client($uri);

try {
    $client->beginTransaction();
    //...
    $client->commit();
} catch (\Throwable $exception) {
    $client->rollBack();
}

或者你可以使用 事务中间件

<?php

$middleware = new PcComponentes\Transaction\SymfonyMessenger\TransactionMiddleware(
    new PcComponentes\Transaction\Driver\MongoDB\MongoDBTransactionalConnection(
        new PcComponentes\Transaction\Driver\MongoDB\Client($uri)
    )
);