IMHO this falls under the wider scope of general error and exception handling.
Some intro ...
The database is essentially a global variable input in your code. If it's unavailable this is the very definition of an unexpected, "exceptional" condition; it should result in an exception. Of course, you explicitly asked how to handle the situation "short of wrapping every database call in if statements." Wrapping each and every DB operation in a try/catch
block is basically the same as wrapping each operation in if
statements.
Further, the mysql_connect
function will raise a PHP error in addition to returning FALSE
if it can't connect. You should really be using PDO
instead of the mysql dinosaur, but that's another topic entirely. Hopefully you aren't using the error suppression operator @
or not reporting E_WARNING
errors to avoid this.
So how to handle it ...
Personally, I would have nothing to do with error handling in PHP. You should define a custom error handler function using set_error_handler
docs that throws an exception on any PHP error and handle exceptions instead of errors.
When you set up your error handling strategy in this manner it's then simple to wrap any functionality that could cause problems or unexpectedly throw in a try
block and handle the unexpected events in your catch
blocks.
Since you stated that, "All of [your] database-facing classes extend a base class which grants them database access," I would suggest adding a simple boolean property to the base class to act as a flag for whether or not the database connection has failed. Then, just check the value of the flag before each attempt to query the database. If you're correctly passing around the database instance in your classes (and not breaking references), they'll all have access to the same property when they need it.
If the database connection failed, you would just set the hypothetical $dbConn->connError = TRUE;
flag in the try block.
So, to summarize, while the specifics of how to structure the actual code depend on exactly what you're doing, using exceptions to handle error conditions is IMHO the most robust way to go about it.