2012-10-27 19 views
1

我有5个数据库的配置文件database.php。如何检查所有数据库的可用性在CI 2

如果某个数据库不可用,如何在所有页面中如何获得500错误消息“网站不可用”?

+0

那么,你是否说你想关闭访问该网站,如果即使一个数据库无法连接? – Brendan

回答

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(), 
); 

因此,一旦控制器已被实例化,但一直运行没有方法还你的钩踢。这是neccesary使用$ 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:[email protected]/db1', 
     'mysqli://user2:[email protected]/db2', 
     'mysqli://user3:[email protected]/db3', 
     'mysqli://user4:[email protected]/db4', 
     'mysqli://user5:[email protected]/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为$ CI - > load-> database()以这种方式,当它试图加载数据库时,我们可以处理错误而不是代码点火器。

希望这会有所帮助。

相关问题