Created
September 5, 2018 12:28
-
-
Save Nex-Otaku/df4f0b42361641417d3449a6a894f487 to your computer and use it in GitHub Desktop.
Автоматическое переподключение в Yii
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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