嘿伙计我对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;
}
Run Code Online (Sandbox Code Playgroud)
}
当实现“工厂”时,通常使用它的其他类、方法等不必知道或关心连接、用户名、密码等。
我会做更多类似的事情:
static class PDOConnectionFactory {
// database
private $dbType = "mysql";
// connection parameters
private $host = "localhost";
private $user = "user";
private $senha = "password";
private $db = "database";
// new CreateNewConnection( true ) <--- persistent connection
// new CreateNewConnection() <--- no persistent connection
public function CreateNewConnection($persistent = false) {
try {
$con = new PDO($dbType . ":host=" . $host . ";dbname=" . $db, $user, $senha, array(PDO::ATTR_PERSISTENT => $persistent));
// carried through successfully, it returns connected
return $con;
}
catch (PDOException $ex) {
// in case that an error occurs, it returns the error;
echo "We are currently experiencing technical difficulties. We have a bunch of monkies working really hard to fix the problem. Check back soon: " . $ex->getMessage();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以按照您需要的任何方式使用 CreateNewConnection() 返回的连接。
我没有检查上面的代码是否可以编译,可能存在一些拼写错误/问题,但你明白了。现在您需要更进一步并实现类似存储库模式的东西:)
| 归档时间: |
|
| 查看次数: |
2251 次 |
| 最近记录: |