php - 我应该在 PDO 对象中返回什么来生成可靠的代码?

标签 php mysql sql pdo

我使用 PDO 编写了一个新的数据库类。不过我正在努力解决一个问题。我通常返回一个对象,这样我就可以使用它。因此,当查询失败时,我只需返回 $this。我有一个名为 wasSuccessful() 的方法,用于确保查询不会失败。

$result = $database->query(...);
if ($result->wasSuccessful()) {
  // do code
}

但是,当该方法返回 false 时我该怎么办?例如:

...
if (!$this->tableExists($table)) return false;

发生这种情况时,PDO 告诉我无法对 bool 值运行函数。我该如何以最好的方式解决这个问题?

提前非常感谢!

最佳答案

您应该使用异常,而不是依赖函数的返回值。像这个简单的例子应该会给你这样的想法:

在你的类(class):

class MyClass {
    public function query($sql, ...$params) {
        if (!$this->tableExists($table)) {
            throw new \Exception("the table doesn't exist");
            return false;
        }
    }
}

然后在您的代码中:

try {
    $result = $database->query(...);
    // do stuff with $result, knowing it's ok
} catch (\Exception $e) {
    echo "here's our error handling routine";
    echo $e->getMessage();
}

在更复杂的项目中,可能需要创建自己的异常类。此外,您还可以在类中使用 try/catch,并将 PDO 中的异常抛出到更高级别的代码。例如:

class MyClass {
    public function query($sql, ...$params) {
        if (!$this->tableExists($table)) {
            throw new \Exception("the table doesn't exist");
            return false;
        }
        try {
            //do something with the PDO object that might throw an exception
        } catch (\PDOException $e) {
            // just take this existing exception and throw it to the next catch block
            throw $e;
            return false;
        }
    }
}

关于php - 我应该在 PDO 对象中返回什么来生成可靠的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668177/

相关文章:

mysql - SQL:在外部查询中保持子查询顺序

javascript - JS - 如何在特定页面执行代码

sql - 这是有效的 Oracle 存储过程吗

php - 将 Div 作为 Google 文档中的页面并粘贴拆分内容?

MySQL : Timestamps replicating inconsistently depending on local timezone of server?

MySQL 自动递增自定义值

php - Laravel 中非常缓慢的 Eloquent 插入/更新查询

mysql 值大于值数量的百分比

php - 仅使用 MySQLi 获取一行

php - 在 MYSQL 中使用哪个子句代替 IN 子句