Do you miss transaction in RDBMS while using MongoDB? You are not alone.
A news said that MongoDB will support ACID in the future, but what if we need it now?
Well, PHP-Mongo-Transaction
provides a simply basic transaction feature similar to RDBMS.
The flow is simple, just begin a transaction, do something, then commit or rollback.
The concept to achieve this is also simple: build a record collection in MongoDB to trace the modification of the data, and recover when rollback.
That is, once a transaction wants to rollback, it will:
- delete what has been inserted
- insert back what has been deleted (with the same ID)
- replace the modified data with the original copy (with the same ID)
To achieve this, this lib wraps the basic insertOne
, updateOne
, deleteOne
functions which provided by MongoDB Driver.
Have a look at #Usage
part of this document to see how easy to use it.
-
We assume the database just works, so if there is a database failure, the transaction may not be rollback correctly and will be leaving as
ongoing
state. You may need to have a cron job to detect if everything works fine, and investigate manually when something goes wrong. If everything goes smoothly, the state of transactions should be eithercommit
orrollback
, except the realinit
andongoing
ones. -
We can't handle concurrency issues at the current stage. It's too complicated to ensure data consist under the concurrent scenario. We recommend that you consider using a simple lock mechanism to avoid two transactions that may write to the same record happen at the same time, or adapting a message queue system to maintain the order of transaction execution.
- More unit tests
- Enhance docs
- Support
insertMany
,updateMany
,deleteMany
You can use Persistable
class with this library, but do not do any magic in the bsonSerialize
and bsonUnserialize
, e.g: auto update the "last modified date".
Any magic in these two functions will definitely destroy the valid data state
composer require lomocoin/php-mongo-transaction
require __DIR__ . '/vendor/autoload.php';
use Lomocoin\Mongodb\Config\TransactionConfig;
use Lomocoin\Mongodb\Transaction\Transaction;
use MongoDB\Client;
$dbName = 'lomocoin_mongodb_test';
$config = new TransactionConfig(
new Client(),
$dbName,
'lomocoin_mongodb_test_transaction_log',
'lomocoin_mongodb_test_transaction_state_change_log');
$transaction = Transaction::begin($config);
$collection = $config->getMongoDBClient()->$dbName->testCollection;
$transaction->insertOne($collection, [
'username' => 'B',
'email' => 'b@example.com',
'name' => 'BB',
]);
$transaction->updateOne($collection, [
'username' => 'B',
], [
'$set' => [
'name' => 'BBB',
],
]);
$transaction->deleteOne($collection, ['username' => 'B']);
// if no error happens, you commit
$transaction->commit();
// if any error happens, you rollback
$transaction->rollback();
Apache License 2.0