编程

PHP 8.3: SQLite3: 新增 \SQLite3Exception、弃用和修改

407 2023-12-18 17:23:00

PHP 8.3 中的 SQLite 扩展改进了该扩展的错误处理,以鼓励使用 Exception,并阻止 PHP 警告的现有行为。

SQLite3 扩展当前默认的错误处理方式是发出 PHP 警告。这在 PHP 8.3 中没有改变,PHP 8.3 和其他 PHP 8.x 版本继续在错误时发出 PHP 警告。SQLite3 扩展提供了一个 SQLite3::enableExceptions(true)方法,该方法将错误处理行为更改为抛出异常,而不是发出 PHP 警告。

在 PHP 8.3 中,有四个与此功能相关的更改:

  • 添加新的 SQLite3Exception Exception 类,它扩展了现有的 \Exception 类。
  • PHP 警告消息中移除了错误代码,并添加了 SQLite3Exception 错误代码 (SQLite3Exception::getCode())。
  • SQLite3::enableExceptions(false) 被弃用。

PHP 8.3 及所有 PHP 8.3+ 版本将继续发出警告。 必须调用 SQLite3::enableExceptions(true) 才能弃用 Exceptions。

新增 SQLite3Exception Exception 类

PHP 8.3 SQLite3 扩展在全局命名空间中添加了新的 Exception 类,它扩展自现有了 \Exception 类。

class SQLite3Exception extends \Exception {}

它不引入任何额外的常量、属性或方法。

The new \SQLite3Exception exception class can be polyfilled in user-land PHP code. While this does not change the behavior of the SQLite3 extension in older PHP versions, it can be helpful if the applications need to serialize and unserialize exceptions across multiple PHP versions including PHP 8.3.

SQLite3 错误码移动到 SQLite3Exception

在 PHP 8.3 之前,SQLite3 扩展发出的 PHP 警告在警告信息中包含错误码。

Unable to prepare statement: 23, not authorized

在 PHP 8.3 中,所有这些信息已经改成在警告信息中不包含错误码。

比如,上述 PHP 警告信息在 PHP 8.3 中改为如下:

- Unable to prepare statement: 23, not authorized
+ Unable to prepare statement: not authorized

PHP 8.3 及之后的版本,要获得错误码,请在 SQLite3 实例中启用  Exception 支持,并检测 Exception 的错误码。

$db = new SQLite3(':memory:');
$db->enableExceptions(true);

$db->setAuthorizer(function () {
    return false;
});

try {
    $db->querySingle('SELECT 1;');
} catch (\SQLite3Exception $e) {
    echo $e->getMessage() . "\n";
    echo $e->getCode();
}

SQLite3::enableExceptions(false) 弃用

SQLite3 扩展继续在所有的 PHP 8.x 版本(包括 PHP 8.3 及之后的版本 )中发出警告。这与隐式调用 SQLite3::enableExceptions(false) 相同。

不过,显式调用 SQLite3::enableExceptions(false) 在 PHP 8.3 及以后被弃用。

$db = new SQLite3(':memory:');
$db->enableExceptions(false);
Deprecated: SQLite3::enableExceptions(): Use of warnings for SQLite3 is deprecated

向后兼容性影响

此更改带来了一些最小的向后兼容性破坏。

  1. SQLite3 扩展的 PHP 警告信息不再包含错误码。
  2. 异常启用后,现在抛出 \SQLite3Exception 异常,而不再是 \Exception。不过,因为 \SQLite3Exception 扩展自 \Exception 类,现有的 catch () 代码块应该可以继续使用。
  3. 调用 SQLite3::enableExceptions(false) 发出弃用警告。