Slim Framework重定向到路由之外(如果数据库出现故障)


Slim Framework redirect outside of a route (if database fails)

这是我的数据库类:

<?php
// Database class
final class Database {
  private static $instance = null;
  public $db;
  private function __construct() {
        global $config;
        global $app;
        $config = (object) $config["database"];
        try {
          $dsn = sprintf("%s:hostname=%s;dbname=%s;", $config->driver, $config->host, $config->dbname);
          $this->db = new PDO($dsn, $config->username, $config->password);
          $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
          $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
        } catch(PDOException $e) {
            // stop app
         // Redirect to /error/database
        }
  }
  public static function getDb() {
    if(Database::$instance == null) Database::$instance = new Database();
    return Database::$instance->db;
  }
}

现在,如果数据库连接失败,我想将用户重定向到/error/database

但是,它不会重定向。我试过

header("Location: /error/database");

$app->redirect("/error/database");

我还尝试创建一个自定义错误处理程序(使用$app->error(function() { ... });和捕获$app->error,但它返回NULL

这个解决方案对我不起作用,可能是因为它使用了SlimFramework2,而我使用的是3?

修复了它,我添加了一个中间件

 // add a middleware, check if we have a database connection
 $app->add(function($req, $res, $next) use($app) {
   if(Database::getDb() == null &&
      !preg_match("/error/", $req->getUri())) {
     return $res
             ->withStatus(500)
             ->withHeader("Location", $app
                                       ->getContainer()
                                       ->router
                                       ->pathFor("error-database"));
   }
   return $next($req, $res);
 });