Php Slim Framework在路由之外重定向(如果数据库失败)
这是我的数据库类:Php Slim Framework在路由之外重定向(如果数据库失败),php,slim,slim-3,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 {
<?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;
}
}
及
我还尝试创建一个自定义错误处理程序(使用$app->error(function(){…});
并在catch$app->error
中返回NULL
不适合我,可能是因为它使用SlimFramework 2,而我使用的是SlimFramework 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);
});
修好了,我加了一个餐具
// 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);
});
为什么stll使用pdo。使用pdo上构建的redbeanphp orm为什么stll使用pdo。使用pdo上构建的redbeanphp orm
// 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);
});