Auto connecting to PDO only if needed

前端 未结 5 2059
不思量自难忘°
不思量自难忘° 2020-12-17 04:27

I have a section of code that depending on the URL requested, will include one of fourteen other files. Some of these fourteen files require a connection to one of three di

5条回答
  •  情深已故
    2020-12-17 04:44

    I took another approach using __call magic method so you don't need to create individual wrappers for every method.

    class PDOLazyConnector
    {
        private $dsn;
        private $username;
        private $password;
        private $driver_options;
        private $dbh;
    
        public function __construct ($dsn, $username, $password, $driver_options = array ())
        {
            $this->dsn = $dsn;
            $this->username = $username;
            $this->password = $password;
            $this->driver_options = $driver_options;
        }
    
        public function __call ($function, $args)
        {
            // connect to db (first time only)
            $this->__init_dbh ();
    
            // invoke the original method
            return call_user_func_array (array($this->dbh, $function), $args);
        }
    
        public function __get ($property)
        {
            return $this->dbh->$property;
        }
    
        private function __init_dbh ()
        {
            // If db handler is not open yet, do it now
            if (empty ($this->dbh)) {
                $this->dbh = new PDO ($this->dsn, $this->username, $this->password, $this->driver_options);
            }
        }       
    }
    

    You just have to replace your PDO instancing with PDOLazyConnector, so:

    $dbh = new PDO($dsn, $user, $password, $driver_options);
    

    with:

    $dbh = new PDOLazyConnector($dsn, $user, $password, $driver_options);
    

提交回复
热议问题