Can function calls occur within a PDO transaction block? This is simplified code (using MySql database)…
try{
$db->beginTransaction();
// call to function that creates user
$user_id = create_user();
// call to function that creates company
$company_id = create_company();
// call to function to link user & company
add_user_to_company($user_id, $company_id);
$db->commit();
}
If this can’t happen using transactions, what is the recommended strategy?
Unless any of those function calls attempts to open or commit a transaction themselves, or use a different connection than the one stored in
$db, yes it should work just fine.The PDO object (or the RDBMS for that matter) doesn’t know or care whether you are calling other functions in PHP. All it knows is if the action is taking place on the same open connection as the one opened in
$db. We assume that those functions either receive$dbas a parameter or access it globally.Remember that although PDO keeps track of transaction state (exposed through
PDO::inTransaction()), it is really the RDBMS which is managing the transaction state, not PDO or the PHP application code. If, a function attempts to open a new transaction before the previous one was committed, MySQL’s documented behavior is to auto-commit the previous transaction since it does not support transaction nesting.So just be sure your additional function calls are not attempting to change the transaction state.