Advertisement
Guest User

Untitled

a guest
Feb 1st, 2017
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. <?php
  2. class ReconnectingPDO
  3. {
  4. protected $dsn, $username, $password, $pdo, $driver_options;
  5.  
  6. public function __construct($dsn, $username = "", $password = "", $driver_options = array())
  7. {
  8. $this->dsn = $dsn;
  9. $this->username = $username;
  10. $this->password = $password;
  11. $this->driver_options = $driver_options;
  12. }
  13.  
  14. public function __call($name, array $arguments)
  15. {
  16. try {
  17. $this->connection()->query("SHOW STATUS;")->execute();
  18. } catch(\PDOException $e) {
  19. if($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) {
  20. throw $e;
  21. }
  22.  
  23. $this->reconnect();
  24. }
  25.  
  26. return call_user_func_array(array($this->connection(), $name), $arguments);
  27. }
  28.  
  29. protected function connection()
  30. {
  31. return $this->pdo instanceof \PDO ? $this->pdo : $this->connect();
  32. }
  33.  
  34. public function connect()
  35. {
  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. {
  43. $this->pdo = null;
  44. return $this->connect();
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement