I've been working to refine my OO approach to PHP. Currently, I'm unable to come to a conclusion on the best approach to handling database connections.
I have 3 main layers to my database interaction:
- The process layer which redirects requests and data to the appropriate objects.
- The objects that contain logic for handling the data
- A database object which handles connecting to the database and queries.
For the objects in layer 2, each object initializes a database connection in its constructor and stores it as a member. This can then be accessed by all the objects methods non-static methods.
The problem scenario:
I have an import class which reads in an excel file (several hundred lines). Each line corresponds to an object. The result is I end up with an array of objects (all of the same type). In each of these objects I have an insert method which connects to the database and stores the data. Because the database connection is established in the constructor I end up with a large number of open connections (or at least I think I do based on my understanding of PDO/OO). When I try to run my inserts for each object in the array I end up exceeding my max-allowed-connections.
Where and how do you handle your database connection so as not to run into this problem?
Here are some code excerpts to understand my problem better:
PHP Code:
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
PHP Code:
//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;
}
}
}
PHP Code:
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;
}
}
Bookmarks