PHP:以面向对象的方式管理连接池

时间:2011-11-14 19:44:20

标签: php oracle oop pdo connection-pooling

我目前正在使用PHP,ORACLE,PDO和JNDI的组合将我的应用程序连接到数据库。我无法理解以面向对象的方法管理连接池的最佳方法。因此,当我尝试进行批量插入时(任何超过32个插入(我的最大池大小设置为)),我都会收到最大连接警告。)

考虑这个例子:

Main File:
//User uploads excel document which I parse into an array
$car = array();
foreach($array as $index => $data){
    $car[$index] = new Car(null,$data["make"],$data["model"]);
    $car[$index]->insert();
}
//return car array of objects

关于班级:

//Car Class
class Car{

    protected $pkey;
    protected $make;
    protected $model;
    protected $db;

    public function __construct($pkey,$make,$model){
        $this->pkey = $pkey;
        if(isset($make) && ($make != '')){
            $this->make = $make;
        }else{
            throw new Exception("Car must have make");
        }
        if(isset($model) && ($model != '')){
            $this->model = $model;
        }else{
            throw new Exception("Car must have model");
        }
        $this->db = new Database();
    }

    public function insert(){
        $sql = "INSERT INTO TABLE (...) VALUES (..)";
        $data = array(
            ":make"=>$this->make,
            ":model"=>$this->model,
        );
        try{
            $this->pkey = $this->db->insert($sql,$data);
            return true;
        }catch(Exception $err){
            //catch errors
            return false;
        }
    }
}

在此示例中,假设max-pool设置为32,任何大于32的数组都将导致我超过max-pool-size,因为每个car对象都存储有一个活动的db连接。为了解决这个问题,我尝试对该类实现以下修复。

//Car Class
class Car{

    protected $pkey;
    protected $make;
    protected $model;
    protected $db;

    public function __construct($pkey,$make,$model){
        $this->pkey = $pkey;
        if(isset($make) && ($make != '')){
            $this->make = $make;
        }else{
            throw new Exception("Car must have make");
        }
        if(isset($model) && ($model != '')){
            $this->model = $model;
        }else{
            throw new Exception("Car must have model");
        }
        //$this->db = new Database(); //Moved out of the constructor
    }

    public function insert(){
        $this->establishDBConn();
        $sql = "INSERT INTO TABLE (...) VALUES (...)";
        $data = array(
            ":make"=>$this->make,
            ":model"=>$this->model,
        );
        try{
            $this->pkey = $this->db->insert($sql,$data);
            $this->closeDBConn();
            return true;
        }catch(Exception $err){
            //catch errors
            $this->closeDBConn();
            return false;
        }
    }

    protected function establishDBConn(){
        if(!$this->db){
            $this->db = new Database();
        }
    }

    public function closeDBConn(){
        if($this->db){
            $this->db->close();
            $this->db = null;
        }
    }
}

理论上,此更改应强制仅在实际插入过程中保持活动连接。但是,通过此更改,我继续达到我的最大连接池限制。作为最后的努力,我将所有插入逻辑移出汽车类并创建了批量插入功能。此函数忽略对象的概念,而只是接收一个数据数组,它循环并插入单个数据连接。这有效,但我很想找到一种方法来解决我在面向对象编程的约束中遇到的问题。

有关如何改进代码以便更有效地使用对象和数据库连接的任何建议?

作为参考,我的数据库类是这样的:

class Database {

    protected $conn;
    protected $dbstr;

    public function __construct() {
        $this->conn = null;
        $this->dbstr = "jndi connection string";
        $this->connect();
    }

    public function connect(){
        try{
            $this->conn = new PDO($this->dbstr); // Used with jndi string
        } catch (PDOException $e){
            //      print $e->getMessage();
        }
        return "";
    }

    public function insert($query, $data){
        try{
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            /* Execute a prepared statement by passing an array of values */
            $sth = $this->conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
            $count = $sth->execute($data);
            return $this->oracleLastInsertId($query);
        }catch(PDOException $e){
            throw new Exception($e->getMessage());
        }
    }
    public function oracleLastInsertId($sqlQuery){
        // Checks if query is an insert and gets table name
        if( preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $sqlQuery, $tablename) ){
            // Gets this table's last sequence value
            $query = "select ".$tablename[1]."_SEQ.currval AS last_value from dual";
            try{
                $temp_q_id = $this->conn->prepare($query);
                $temp_q_id->execute();
                if($temp_q_id){
                    $temp_result = $temp_q_id->fetch(PDO::FETCH_ASSOC);
                    return ( $temp_result ) ? $temp_result['LAST_VALUE'] : false;
                }
            }catch(Exception $err){
                throw new Exception($err->getMessage());
            }
        }
        return false;
    }

    public function close(){
        $this->conn = null;
    }
}

1 个答案:

答案 0 :(得分:0)

正确的方法似乎是使用基于单例的数据库类:

class Database { 

    protected $conn; 
    protected $dbstr; 

    // keep the one and only instance of the Database object in this variable
    protected static $instance;

    // visibility changed from public to private to disallow dynamic instances
    private function __construct() { 
        $this->conn = null; 
        $this->dbstr = "jndi connection string"; 
        $this->connect(); 
    } 

    // added this method
    public static function getInstance() {
      if (!isset(self::$instance)) {
        self::$instance = new Database();
      }
      return self::$instance;
    }

    // everything below this comment is as it was; I made no changes here
    public function connect(){ 
        try{ 
            $this->conn = new PDO($this->dbstr); // Used with jndi string 
        } catch (PDOException $e){ 
            //      print $e->getMessage(); 
        } 
        return ""; 
    } 

    public function insert($query, $data){ 
        try{ 
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
            /* Execute a prepared statement by passing an array of values */ 
            $sth = $this->conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); 
            $count = $sth->execute($data); 
            return $this->oracleLastInsertId($query); 
        }catch(PDOException $e){ 
            throw new Exception($e->getMessage()); 
        } 
    } 
    public function oracleLastInsertId($sqlQuery){ 
        // Checks if query is an insert and gets table name 
        if( preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $sqlQuery, $tablename) ){ 
            // Gets this table's last sequence value 
            $query = "select ".$tablename[1]."_SEQ.currval AS last_value from dual"; 
            try{ 
                $temp_q_id = $this->conn->prepare($query); 
                $temp_q_id->execute(); 
                if($temp_q_id){ 
                    $temp_result = $temp_q_id->fetch(PDO::FETCH_ASSOC); 
                    return ( $temp_result ) ? $temp_result['LAST_VALUE'] : false; 
                } 
            }catch(Exception $err){ 
                throw new Exception($err->getMessage()); 
            } 
        } 
        return false; 
    } 

    public function close(){ 
        $this->conn = null; 
    } 
}