【问题标题】:What shall I return in a PDO Object to produce reliable code?我应该在 PDO 对象中返回什么来生成可靠的代码?
【发布时间】:2019-04-13 17:36:04
【问题描述】:

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

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

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

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

当这种情况发生时,PDO 告诉我我不能在布尔值上运行函数。我该如何以最好的方式解决这个问题?

提前非常感谢!

【问题讨论】:

  • throw exceptions而不是返回false。
  • 假设您的第二段代码是您的数据库类的一部分,并且鉴于您之前所说的,逻辑将指示return $this; 而不是return false; 并使用...->wasSuccessful() 来检查成功或失败.另一方面,检查布尔值并不困难。但是,一种方法不能同时使用两种返回机制,因为那样您将不知道如何检查它。也就是说,例外也很好。

标签: php mysql sql pdo


【解决方案1】:

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

在你的课堂上:

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 到更高级别代码的throw 异常。例如:

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

【讨论】:

  • 谢谢,会实现这个!最近没有检查答案,所以请不要认为您的努力没有得到赞赏!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2011-01-30
  • 2012-01-05
  • 2012-08-19
  • 1970-01-01
  • 2015-01-07
相关资源
最近更新 更多