嗨,大家好,我对于pdo来说很新,所以我基本上只是使用我正在阅读的介绍性书籍中的信息将一个简单的连接类放在一起,但这种连接是否有效?如果有人有任何丰富的建议,我会很感激。任何改善我的PDO连接类的建议?
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;
}
}
我会重新命名'公共$ persistent'到'公共$ isPersistent'(口味有物质),也可以调整构造'if'线,而不是看只是简单的'$这个 - > isPersistent = $ persistent;'。其他'公共'变量($ con,$ dbType,$ host,$ user,$ senha,$ db)可能应该是'private'。在实施“工厂”时,通常是这样的,其他类,方法等使用它不必知道或关心连接,用户名,密码等。 – 2010-06-09 21:43:20
欣赏它。 – Scarface 2010-06-09 22:08:02
你知道这个过程是否有效吗?有没有更好的办法?我还没有时间更深入地学习编码模式和面向对象编程,所以我只是在寻找一个可以开始的地方,所以我可以维持我的网站,直到我更新它。 – Scarface 2010-06-09 22:11:26