Skip to content

Instantly share code, notes, and snippets.

@Nex-Otaku
Created September 5, 2018 12:28
Show Gist options
  • Save Nex-Otaku/df4f0b42361641417d3449a6a894f487 to your computer and use it in GitHub Desktop.
Save Nex-Otaku/df4f0b42361641417d3449a6a894f487 to your computer and use it in GitHub Desktop.
Автоматическое переподключение в Yii
<?php
namespace common\components\export_wp_to_blog\helpers;
use yii\db\Connection;
/**
* Операции извлечения занимают длительное время,
* из-за этого SQL-соединение периодически отваливается.
*
* Чтобы этого не происходило, перед выполнением запроса вызываем
* $db->ensureConection();
*
* @author Nex Otaku <nex@otaku.ru>
*/
class RestorableDbConnection extends Connection
{
public function ensureConnection()
{
try {
$this->createCommand('select 1')->execute();
} catch (\yii\db\Exception $e) {
$message = $e->getMessage();
if (strpos($message, 'gone away') === false) {
throw $e;
}
echo "Соединение БД утеряно. Переподключаемся.\n";
$this->close();
$this->open();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment