我已经为简单的 MVC 模式建立了新的数据库连接类。
我需要知道这是正确的方法。
<?php
include_once 'config.php';
class dbModel{
private $dbSys = "";
private $dbHost = "";
private $dbUser = "";
private $dbPass = "";
private $dbName = "";
private con = false;
public function __construct(){
$this->dbSys = DB_SYS;
$this->dbHost = DB_HOST;
$this->dbUser = DB_USER;
$this->dbPass = DB_PASS;
$this->dbName = DB_NAME;
if (!$this->con){
try{
$this->con = new PDO($this->dbSys.':host='.$this->dbHost.';dbname='.$this->dbName, $this->dbUser, $this->dbPass);
return $this->con;
} catch (PDOException $e){
echo $e->getMessage();
exit();
}
}else{
return $this->con;
}
}
}
?>
我将用于数据库配置的config.php文件作为单独的文件包含在内。我正在我的项目中的其他模型中从这个数据库连接类创建新对象,并编写 sql 并运行查询。
我测试了这段代码,这是有效的。但我需要知道这种正确的方式。
请让我知道这是正确的方法。