Codeigniter AutoLoad DB, But have ability to check

2019-08-10 12:50发布

问题:

How would I autoload the database using autoload.php

I already got the autoloading of course... that's the easy part.

But also allowing me to check if the db has been connected to, and if not, to display a specific page saying something like "We are sorry but our database is currently unavailable."

Would it have to be some kind of custom hook that I would have to make?

回答1:

You can edit the error template in application/errors/error_db.php to use your custom message. Maybe use the ENVIRONMENT constant and do something like this:

<?php if (ENVIRONMENT === 'production'): ?>
  <p>We are sorry but our database is currently unavailable.</p>
<?php else: ?>
  <!-- default template with actual database error messages -->
<?php endif; ?>

Otherwise, I suppose you could use a hook. It would have to be at least pre_controller if you are auto loading the database class and want to intercept the error, or you could just load the database class in the __construct() of a MY_Controller class after doing your connection check. You could even just do it right in the first line of index.php if you wanted to.

However: I think what you're looking for might be in the language files. Take a look at:
system/language/english/db_lang.php.
If you create your own file in the same place, but in /application instead of /system, you can just rewrite the appropriate language line(s):

// $lang['db_unable_to_connect'] = 'Unable to connect to your database server using the provided settings.';
$lang['db_unable_to_connect'] = 'We are sorry but our database is currently unavailable.';

...and just edit the CSS and/or markup in the error template. Once again, you can take advantage of the ENVIRONMENT constant to show useful errors in development mode, and show user-friendly ones in production.

Of course, if you can't connect to your database - that's a major problem that needs immediate attention.