PHP PDO注入一个类

时间:2018-06-01 10:12:11

标签: php pdo

我试图了解如何在课堂内使用PDO。我写了这个简单的类,它持有一个PDO连接,它作为另一个类中__construct()的一部分传递。问题是,每当我尝试使用需要数据库连接的类的方法时,我都会收到一条与PDO内置函数(如prepare())相关的错误消息, execute()。错误为PHP Fatal error: Uncaught Error: Call to undefined method Database::prepare()。我怎么能解决这个问题?我已经阅读了关于依赖注入的内容,但是现在使用PDO

时如何将这种模式应用于代码有点令人困惑
<?php

class Database {

    public function __construct() {

        return $this->db = new PDO("mysql:host=localhost;dbname=testdb;", "root", "root");
    }

}

class user {

    public function __construct($db) {

        $this->db = $db;
    }

    public function createUser($email, $username, $password) {

        $stmt = $this->db->prepare("INSERT INTO users (email,username,password) VALUES (?, ?, ? )");
        if ($stmt->execute(array($email, $username, $password))) {
            echo "Account successful created";
        } else {
            echo "Something was wrong during the registration process.";
        }
    }

    public function loginUser($username, $password) {

        $stmt = $this->db->prepare("SELECT email,username,password FROM users WHERE email = ? OR username = ?");

        $stmt->execute(array($username, $username));
        if ($stmt->rowCount() > 0) {
            $result = $stmt->fetch(PDO::FETCH_OBJ);
            if (password_verify($password, $result->password)) {
                echo "logged";
            } else {
                echo "wrong password";
            }
        } else {
            echo "Username or email does not exist in the database.";
        }
    }

}

1 个答案:

答案 0 :(得分:0)

如果要将PDO连接封装在额外的类中,则应为实际连接创建一个getter

<?php 
    class Database {
        private $dbh = null;

        public function __construct($user, $pass, $database) {
            $this->dbh = new PDO("mysql:host=localhost;dbname=".$database.";", $user, $pass);
        }

        public function getConnection() {
            return $this->dbh;
        }
    }

    class User {
        private $db = null;

        public function __construct($db) {
            $this->db = $db;
        }

        public function createUser($email, $username, $password) {
            $stmt = $this->db->getConnection()->prepare("INSERT INTO users (email,username,password) VALUES (?, ?, ? )");
            if ($stmt->execute(array($email, $username, $password))) {
                echo "Account successful created";
            }else {
                echo "Something was wrong during the registration process.";
            }
        }       
    }

}

$user = new User(new Database('root', 'root', 'testdb'));

来自评论:

最好将你的PDO实例传递给你的班级。这应该有效:

<?php
class user {
    public function __construct(\PDO $db) {
        $this->db = $db;
    }
}
<?php
    /** Init the one and only DB connection for this request **/
   $dbh = new PDO("mysql:host=localhost;dbname=".$database.";", $user, $pass);

   //... Do some stuff
   //....
   $user = new User($dbh);