1

我有 5 个数据库的配置文件 database.php。

如果其中一个数据库不可用,如何在所有页面中收到 500 错误消息“站点不可用”?

4

1 回答 1

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");                
      }
    }

  }
}

您必须为 $CI->load->database() 使用 dsn,这样我们可以在尝试加载数据库时处理错误而不是 Code Igniter。

希望这可以帮助。

于 2012-10-28T10:31:31.083 回答