Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class BetterPDO
- {
- protected $dsn, $username, $password, $pdo, $driver_options;
- const RETRY_ATTEMPTS = 3;
- public function __construct($dsn, $username = "", $password = "", $driver_options = array()) {
- $this->dsn = $dsn;
- $this->username = $username;
- $this->password = $password;
- $this->driver_options = $driver_options;
- $this->connect();
- }
- public function __call($method, $arguments){
- $retry = 0;
- try_again:
- try {
- return call_user_func_array(array($this->pdo, $method), $arguments);
- } catch(\Exception $e) {
- if($retry >= self::RETRY_ATTEMPTS || $e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away')) {
- throw $e;
- }
- ++$retry;
- $this->reconnect();
- goto try_again;
- }
- }
- public function connect() {
- $this->pdo = new \PDO($this->dsn, $this->username, $this->password, (array) $this->driver_options);
- $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
- return $this->pdo;
- }
- public function reconnect() {
- $this->pdo = null;
- return $this->connect();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement