dmlogic/pdo-retry-wrapper

此软件包最新版本(v0.1)没有可用的许可信息。

PDO包装器,用于优雅地处理断开连接

v0.1 2021-10-05 07:34 UTC

This package is auto-updated.

Last update: 2024-09-05 13:49:28 UTC


README

我希望不必这样做。但AWS下的RDS并不像所声称的那样可用。

这受到illuminate/database中内置的断开连接重试机制的启发。我想在这里实现同样的功能,但针对PDO的级别要低得多。

提供以下功能

  • 重试因连接问题而失败的查询,最多尝试指定次数
  • 定义一个回调函数,在达到限制时运行
  • $pdo->prepare($sql)$pdo->execute($bindings)合并为一个$connection->runQuery($sql, $bindings)调用

用法

// Connector is a Closure for simpler reconnects
$pdoConnector = function() {
    return new PDO(
            'dsnString',
            'username',
            'password',
            [
                PDO::OPTION_NAME => VALUE,
                ...
            ]
        );
};

// Optional exception callback can be anything at all
// It's a handy place to centralise the error handling
// logic if you don't want queries inside try/catch
$callback = function(ConnectionException $exception) {
    $exception->getAttempts();
    $exception->getOriginalException();
    $exception->getQuery();
    $exception->getBindings();
}

// Create the wrapper
$dbConnection = new Connection($pdoConnector, $callback);

// Generate a PDOStatement with results
try {
    $query = $dbConnection->runQuery('select * from users where id = ?', [123]);
    $user = $query->fetch(PDO::FETCH_OBJ);
} catch(ConnectionException $e) {
    // We know we failed on connection
    // $callback has been invoked at this stage
} catch(Exception $e) {
    // Something else went down
}