我有这个PDO数据库类
class clsDatabase{ // db settings private $host = 'localhost'; private $user = 'test'; private $dbname = 'test'; private $pass = 'test1'; private $dbh; private $error; public function __construct(){ // Set DSN $dsn = 'mysql: host=' . $this->host . ';dbname=' . $this->dbname; // Set options $options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8' ); // Create a new PDO instanace try{ $this->dbh = new PDO($dsn, $this->user, $this->pass, $options); } // Catch any errors catch(PDOException $e){ $this->error = $e->getMessage(); echo $this->error; exit; } } public function query($query){ $this->stmt = $this->dbh->prepare($query); } }
我尝试将代码分成不同的类,例如,我有一个连接到clsUserController的clsDBUser。我这样做是为了知道什么类使用什么数据库代码。我的clsDBUser类看起来像这样
class clsDBUser extends clsDatabase { // construct public function __construct() { parent::__construct(); } // get users public function getUsers($users_id){ $query = " SELECT email FROM users WHERE users_id = :users_id "; $this->query($query); $this->bind(':users_id', $users_id); if($row = $this->single()){ $this->close(); return $row; } $this->close(); return false; } }
我想知道这是否可行,还是我现在在每个类中创建一个新的数据库连接?因为通常在PHP4中(是的,我知道很旧),我无法识别我每次都必须建立一个新的数据库连接。
我需要改进吗,我需要如何改进呢?
您应该走空先生的答案中所示的道路。简而言之:
所以应该像
class clsDBLogin { public function __construct($db) { $this->db = $db; } public function validateLogin($email) { $email = trim($email); // Check user in db to start verification $query = 'SELECT * FROM users u, users_info ui WHERE u.users_id = ui.users_id AND u.email = ?'; $stmt = $this->db->prepare($query); $stmt->execute([$email]); return $stmt->fetch(); } } $dsn = 'mysql: host=localhost;dbname=test;charset=utf8'; $options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ); // Create a new PDO instanace $pdo = new PDO($dsn, $this->user, $this->pass, $options); $DBLogin = new clsDBLogin($pdo); $user = $DBLogin->validateLogin($email);