我有配置文件database.php,包含5个数据库。
如果其中一个数据库不可用,如何在所有页面中显示“网站不可用”的500错误?
答案 0 :(得分:1)
我发现你的问题非常有趣,并且一直在做一些研究来解决你的问题。 我告诉你我的解决方案:第一个是激活钩子,所以在你的config.php文件中进行这个改变:
$config['enable_hooks'] = TRUE;
一旦激活了钩子,你需要创建一个新的钩子,因为它在文件config / hooks.php中输入如下内容:
$hook['post_controller_constructor'] = array(
'class' => 'DBTest',
'function' => 'index',
'filename' => 'dbtest.php',
'filepath' => 'hooks',
'params' => array(),
);
因此,一旦控制器被实例化,你的钩子就会启动,但是还没有运行任何方法。这是使用$ CI =& get_instance()
的必要条件完成创建文件/application/hooks/dbtest.php,其内容类似于以下内容:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class DBTest {
function index() {
$CI = &get_instance();
$databases = array(
'mysqli://user1:pass1@host1/db1',
'mysqli://user2:pass2@host2/db2',
'mysqli://user3:pass3@host3/db3',
'mysqli://user4:pass4@host4/db4',
'mysqli://user5:pass5@host5/db5',
);
foreach ($databases as $dsn) {
$db_name = substr(strrchr($dsn, '/'), 1);
$CI->load->database($dsn);
$CI->load->dbutil();
if(!$CI->dbutil->database_exists($db_name)) {
// if connection details incorrect show error
show_error("Site is not available: can't connect to database $db_name");
}
}
}
}
您必须使用dsn for $ CI-&gt; load-&gt; database()这样我们可以在尝试加载数据库时处理错误而不是Code Igniter。
希望这有帮助。