我很少在失败时对数据库查询使用唯一的错误消息
我经常使用简短的标准消息,例如“数据库错误/失败。请与网站管理员联系”或类似的消息。或自动发送给我
我正在寻找一种在PDO中全局设置一次try {}和catch {}的方法。所以我不必一遍又一遍地写
那可能吗?也许把它包装成一小堂课?
最佳答案
在良好的设计应用程序中,您将使用设计模式进行编写。例如,您可以使用MVC方法实现此目的:
模型
class Students {
private pdo;
function __construct($pdo){
//do something
$this->pdo = $pdo;
}
function get_all_students(){
$stmt = $this->pdo->prepare("SELECT * FROM Students");
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
}
Controller
class StudentsController{
function GetStudentAction(){
//here you create an instance of that model
$students_model = new Students();
$students = $students_model->get_all_students();
return $students;
}
}
用法
<?php
include 'Students.php';
include 'StudentsController.php';
try {
$students = new StudentController();
$all_students = $students->GetStudentAction();
//then you have more other models
//for example:
$professors = new ProfessorsController();
$math_professors = $professors->GetMathProfessorsAction();
}
catch( PDOException $Exception ) {
//do something with the Exception
echo( $Exception->getMessage( ) , $Exception->getCode( ) );
}
?>
关于php - 对所有PDO查询进行一次全局尝试{}捕获{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24687458/