Advertisement
Guest User

PDO Gone Away Reconnect

a guest
May 26th, 2018
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.08 KB | None | 0 0
  1. class BetterPDO
  2. {
  3.     protected $dsn, $username, $password, $pdo, $driver_options;
  4.  
  5.     const RETRY_ATTEMPTS = 3;
  6.  
  7.     public function __construct($dsn, $username = "", $password = "", $driver_options = array()) {
  8.         $this->dsn = $dsn;
  9.         $this->username = $username;
  10.         $this->password = $password;
  11.         $this->driver_options = $driver_options;
  12.  
  13.         $this->connect();
  14.     }
  15.  
  16.     public function __call($method, $arguments){
  17.  
  18.         $retry = 0;
  19.         try_again:
  20.  
  21.         try {
  22.             return call_user_func_array(array($this->pdo, $method), $arguments);
  23.         } catch(\Exception $e) {
  24.  
  25.             if($retry >= self::RETRY_ATTEMPTS || $e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) {
  26.                 throw $e;
  27.             }
  28.  
  29.             ++$retry;
  30.             $this->reconnect();
  31.             goto try_again;
  32.         }
  33.     }
  34.  
  35.     public function connect() {
  36.         $this->pdo = new \PDO($this->dsn, $this->username, $this->password, (array) $this->driver_options);
  37.         $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  38.         return $this->pdo;
  39.     }
  40.  
  41.     public function reconnect() {
  42.         $this->pdo = null;
  43.         return $this->connect();
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement