本文介绍了类内的PHP PDO注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to understand how to use PDO inside a class. I wrote this simple class that hold a PDO connection who is passed as a part of the __construct() inside another class. The problem is that everytime I try to use the method of the class who need the database connection, I recive an error message that is related to the PDO's built in functions like prepare(), execute().The error is PHP Fatal error: Uncaught Error: Call to undefined method Database::prepare(). How i can solve this problem? I've read about dependency injection but for now it's a little bit confusing on how to apply this pattern to the code when using 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.";
        }
    }

}

推荐答案

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

You should create a getter for the actual connection if you want to encapsulate the PDO connection in an extra class

<?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'));


从评论中:


From the comments:

对于您的情况,最好将PDO的实例传递给您的类.这应该起作用:

It would be better for your case to just pass an instance of PDO towards your classes. This should work:

<?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);

这篇关于类内的PHP PDO注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:24