Slim Framework重定向到路由之外(如果数据库失败)

时间:2015-12-14 17:06:49

标签: php slim slim-3

这是我的数据库类:

<?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() { ... });并在catch $app->error但是它返回NULL

This solution对我不起作用,也许是因为它使用了SlimFramework 2而我使用的是3?

1 个答案:

答案 0 :(得分:0)

修正了它,我添加了一个middelware

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