【发布时间】:2010-06-09 21:30:20
【问题描述】:
我对 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;
}
}
【问题讨论】:
-
我会将
public $persistent重命名为public $isPersistent(这里的口味问题),并且还将构造函数if行改为简单地读取$this->isPersistent = $persistent;。其他public变量($con、$dbType、$host、$user、$senha、$db)可能应该是private。在实现“工厂”时,通常使用它的其他类、方法等不必知道或关心连接、用户名、密码等。 -
你知道这个过程是否有效吗?有没有更好的办法?我还没有时间更深入地学习编码模式和 OOP,所以我只是在寻找一个开始的地方,这样我就可以维持我的网站,直到我更新它。
-
这是“更好的方式”的开始。如果您练习关注点分离,那么以后维护代码时就不会那么辛苦了。但是,如果您将 mysql 连接对象和 select 语句字符串散布在您的页面上,您将会遇到问题。相反,如果你使用一个类来分离你的数据库层,甚至像创建一个名为
DataAccessLayer的类和一个名为GetThing()的函数,然后是$dal = new DataAccessLayer()并调用$dal->GetThing()这样简单,你将更容易维护你的代码.