Created
May 25, 2013 19:41
-
-
Save xtraclass/5650505 to your computer and use it in GitHub Desktop.
Simple wrapper function which connects to a database system, performs a given function on the database, and closes the database connection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This method calls the given function. | |
* <p> | |
* This method can be used to do something within the database without thinking about opening and closing a database connection. | |
* <p> | |
* First it opens a database connection, if none is open. | |
* Then it calls the given function. | |
* Finally it closes the database connection, if one is open. | |
* <p> | |
* If an exception is thrown within the given function, this method re-throws it. | |
* <br> | |
* If opening or closing the database connection causes an exception, then that exception is thrown, unless | |
* the given function has thrown one, then the exception of the given function is re-thrown. | |
* | |
* @param $function | |
* @throws Exception | |
* @throws Ambigous <NULL, Exception> | |
*/ | |
protected function doInDB( $function ) | |
{ | |
/** | |
* Stores the exception thrown in the given function, | |
* so that it can be re-thrown. | |
*/ | |
$exceptionInFunction = NULL; | |
try | |
{ | |
$this->connect(); | |
try | |
{ | |
$function( $this ); | |
} | |
catch ( Exception $x2 ) | |
{ | |
$exceptionInFunction = $x2; | |
} | |
$this->close(); | |
if ( !is_null( $exceptionInFunction ) ) | |
{ | |
throw $exceptionInFunction; | |
} | |
} | |
catch ( Exception $x1 ) | |
{ | |
$this->close(); | |
if ( is_null( $exceptionInFunction ) ) | |
{ | |
throw $x1; | |
} | |
else | |
{ | |
throw $exceptionInFunction; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment