I have a do...while loop and a try...catch block that wraps around database centric code. The do...while and try...catch serves the purpose of preventing transaction deadlocks, and it does so very well from extensive testing. My problem now is code redundancy. I cannot figure out a way to deploy a function or method that performs the do...while and try...catch around a generic set of database centric code without using the "evil" eval command. I imagine this comes up under other software design pattern scenarios.
This illustrates how I imagine the method with eval:
class Database {
public static function deadlockSafeTransaction($code) {
do {
// setup a condition
try {
// start transaction
eval($code); //evil
// commit transaction
}
catch(Exception $ex) {
// rollback transaction
// analyze exception for deadlock and adjust condition or rethrow exception
}
} while(condition);
}
}
This illustrates an undesired coding practice if I were to use the method above:
// code
Database::deadlockSafeTransaction("
// code - sometimes a lot of complicated code with other method calls and loops
");
// code
I am looking for a solution that does not include the use of the eval command.
After writing all of this up, I just thought of the possibility of flanking my code with include statements:
include "do-try.php";
// database code
include "catch-while.php";
But I am looking for something more OOPish and less hackish. I don't even know if the above would work and the includes may carry an unnecessary performance expense. So the issue still warrants inquiry and discussion for the best solution.