Method Documentation: transaction
Purpose
The transaction
method facilitates the execution of a group of operations within a single database transaction. This method ensures atomicity of a sequence of operations: either all operations succeed, in which case the transaction is committed, or if any operation fails, the entire transaction is rolled back. This approach is crucial for maintaining the integrity of the database state during complex operations that should either completely succeed or fail as a whole.
Parameters
callable[] $operations
- An array of callable functions, each representing a database operation to be executed within the transaction. These callables are executed in sequence, and each should perform a single cohesive operation.
Return Value
This method does not return a value. Its successful completion indicates that all operations within the transaction have been executed and committed without error.
Error Handling
If any of the operations within the transaction fail, the method throws an exception, and the transaction is rolled back. This behavior ensures that the database state remains consistent by not partially applying operations that are meant to be atomic.
Example Usage
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$operations = [
function() use ($prisma) { $prisma->user->create([
'data' => [
'name' => 'John Doe'
]
]);
},
function() use ($prisma) { $prisma->order->create([
'data' => [
'userId' => 1,
'product' => 'Book'
]
]);
}
];
try {
$prisma->transaction($operations);
echo "Transaction successful.";
} catch (\Exception $e) {
echo "Transaction failed: " . $e->getMessage();
}