@@ -1540,6 +1540,73 @@ public function testCausalConsistency()
15401540 ob_end_clean ();
15411541 }
15421542
1543+ /**
1544+ * @doesNotPerformAssertions
1545+ */
1546+ public function testWithTransactionExample ()
1547+ {
1548+ $ this ->skipIfTransactionsAreNotSupported ();
1549+
1550+ $ uriString = static ::getUri (true );
1551+
1552+ // phpcs:disable SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly
1553+ // Start Transactions withTxn API Example 1
1554+ /*
1555+ * For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
1556+ * uriString = 'mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl'
1557+ * For a sharded cluster, connect to the mongos instances; e.g.
1558+ * uriString = 'mongodb://mongos0.example.com:27017,mongos1.example.com:27017/'
1559+ */
1560+
1561+ $ client = new \MongoDB \Client ($ uriString );
1562+
1563+ // Prerequisite: Create collections. CRUD operations in transactions must be on existing collections.
1564+ $ client ->selectCollection (
1565+ 'mydb1 ' ,
1566+ 'foo ' ,
1567+ [
1568+ 'writeConcern ' => new \MongoDB \Driver \WriteConcern (\MongoDB \Driver \WriteConcern::MAJORITY , 1000 ),
1569+ ]
1570+ )->insertOne (['abc ' => 0 ]);
1571+
1572+ $ client ->selectCollection (
1573+ 'mydb2 ' ,
1574+ 'bar ' ,
1575+ [
1576+ 'writeConcern ' => new \MongoDB \Driver \WriteConcern (\MongoDB \Driver \WriteConcern::MAJORITY , 1000 ),
1577+ ]
1578+ )->insertOne (['xyz ' => 0 ]);
1579+
1580+ // Step 1: Define the callback that specifies the sequence of operations to perform inside the transactions.
1581+
1582+ $ callback = function (\MongoDB \Driver \Session $ session ) use ($ client ) {
1583+ $ client
1584+ ->selectCollection ('mydb1 ' , 'foo ' )
1585+ ->insertOne (['abc ' => 1 ], ['session ' => $ session ]);
1586+
1587+ $ client
1588+ ->selectCollection ('mydb2 ' , 'bar ' )
1589+ ->insertOne (['xyz ' => 999 ], ['session ' => $ session ]);
1590+ };
1591+
1592+ // Step 2: Start a client session.
1593+
1594+ $ session = $ client ->startSession ();
1595+
1596+ // Step 3: Use with_transaction to start a transaction, execute the callback, and commit (or abort on error).
1597+
1598+ $ transactionOptions = [
1599+ 'readConcern ' => new \MongoDB \Driver \ReadConcern (\MongoDB \Driver \ReadConcern::LOCAL ),
1600+ 'writeConcern ' => new \MongoDB \Driver \WriteConcern (\MongoDB \Driver \WriteConcern::MAJORITY , 1000 ),
1601+ 'readPreference ' => new \MongoDB \Driver \ReadPreference (\MongoDB \Driver \ReadPreference::RP_PRIMARY ),
1602+ ];
1603+
1604+ \MongoDB \with_transaction ($ session , $ callback , $ transactionOptions );
1605+
1606+ // End Transactions withTxn API Example 1
1607+ // phpcs:enable
1608+ }
1609+
15431610 /**
15441611 * Return the test collection name.
15451612 *
0 commit comments