【问题标题】:One global try{} catch{} for all PDO queries一个全局 try{} catch{} 用于所有 PDO 查询
【发布时间】:2014-09-01 11:20:44
【问题描述】:

我很少在数据库查询失败时使用唯一的错误消息

我经常使用简短的标准消息,例如“数据库错误/失败。请联系网站管理员”或类似的内容。或者让它自动给我发电子邮件

我正在寻找一种在 PDO 中为所有查询设置 try{} 和 catch{} 的方法,在全局范围内。所以我不必一遍又一遍地写同样的东西

这可能吗?也许把它包在一个小课堂里?

【问题讨论】:

  • “也许把它包在一个小课堂里?”您回答了自己的问题。
  • 好吧,我对课程了解不多;)希望能得到一点帮助
  • 那么你也可以使用一个函数来完成它,要么使用全局变量进行连接,要么将连接作为参数传入。
  • 啊,是的,连接已经“全局”了:class DBi { public static $conn; }
  • @mowgli 我的帖子回答了你的问题吗?告诉我

标签: php mysql pdo error-handling try-catch


【解决方案1】:

在一个设计良好的应用程序中,您将使用设计模式编写。例如,您可以使用 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;
    }

}

控制器

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

?>

【讨论】:

  • 这不是在不必要地扩展本机 PDO 吗?而且您仍然为查询设置 try / catch
  • ectending是什么意思
  • 我认为这一切完全没有理由。这如何针对我的问题?
  • 有时您还没有为某些概念做好准备,请随时重新访问此答案
  • 好的,但是请再读一遍我的问题,然后看看你的答案;)
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
相关资源
最近更新 更多