I am pretty new to pdo, so I basically just put together a simple connection class using information out of the introductory book I was reading. But is this connection efficient? If anyone has any informative suggestions, I would really appreciate it.
class PDOConnectionFactory{
public $con = null;
// swich database?
public $dbType = "mysql";
// connection parameters
public $host = "localhost";
public $user = "user";
public $senha = "password";
public $db = "database";
public $persistent = false;
// new PDOConnectionFactory( true ) <--- persistent connection
// new PDOConnectionFactory() <--- no persistent connection
public function PDOConnectionFactory( $persistent=false ){
// it verifies the persistence of the connection
if( $persistent != false){ $this->persistent = true; }
}
public function getConnection(){
try{
$this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha,
array( PDO::ATTR_PERSISTENT => $this->persistent ) );
// carried through successfully, it returns connected
return $this->con;
// in case that an error occurs, it returns the error;
}catch ( PDOException $ex ){ echo "We are currently experiencing technical difficulties. ".$ex->getMessage(); }
}
// close connection
public function Close(){
if( $this->con != null )
$this->con = null;
}
}
When implementing a “Factory” usually it is so that other classes, methods, etc using it don’t have to know or care about the connections, usernames, passwords, etc.
I would do it something more like:
Then you use the connection returned by CreateNewConnection() in whatever way you need.
I didn’t check if the above code compiles, there could be a few typos/issues, but you get the idea. Now you need to take it a step further and implement something like the repository pattern 🙂