访问另一个类中的PDO对象

时间:2014-03-02 14:59:35

标签: php object pdo

我正在尝试访问我创建的类中的PDO对象,但它会引发错误:

  

调用未定义的方法EntelDB :: prepare()

以下是代码。如何访问PDOprepare()等原生query()方法?

class DB
{
    private $dbName = '';
    private $dbUsername = '';
    private $dbPassword = '';
    static protected $instance;
    public $conn;

    protected function __construct($dbName, $dbUsername, $dbPassword)
    {
        $this->dbName = $dbName;
        $this->dbUsername = $dbUsername;
        $this->dbPassword = $dbPassword;
        $this->conn = new PDO("mysql:host=localhost;dbname=" . $this->dbName . ";charset=utf8",
            $this->dbUsername, $this->dbPassword);

        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public static function getInstance($dbName, $dbUsername, $dbPassword)
    {
        if (!self::$instance)
        {
            self::$instance = new self($dbName, $dbUsername, $dbPassword);
        }

        return self::$instance;
    }
}


class Auth
{       
    private $loginQuery = "SELECT userIdusername,password FROM login WHERE username=? AND password=?";
    public $conn;

    function login($username, $password)
    {
        /*here's the DB class usage*/
        $this->conn = DB::getInstance("patikana", "root", "");  
        $_SESSION['user_allow'] = FALSE;
        $_SESSION['user'] = '';
        $_SESSION['userId'] = '';
        $_SESSION['loggedInTime'] = '';
        $query = $this->loginQuery;
        /*
            NOT ACCESSING PREPARE METHODS.
        */
        $stmt = $this->conn->prepare($query);
    }   
}


//instatiation and usage.
$userAuthenticate = new Auth();
$userAuthenticate->login();

1 个答案:

答案 0 :(得分:2)

您正在使用单例模式,但您也希望将“conn”变量作为Auth类中的公共属性。

向Auth类添加构造函数:

public function __construct()
{
  $this->conn = DB::getInstance()->conn;
}

在行中:

$this->conn= DB::getInstance("patikana","root","");

您没有附加连接,而是附加数据库对象实例。

还要考虑使用依赖注入而不是单例。 Singleton是一个难以维护的反模式。

我建议重构:

class Auth {

private $loginQuery="SELECT userIdusername,password FROM login WHERE username=? AND password=?";
private $db;

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

function login($username, $password) {

    $_SESSION['user_allow']=FALSE;
    $_SESSION['user']='';
    $_SESSION['userId']='';
    $_SESSION['loggedInTime']='';
    $query = $this->loginQuery;

    $stmt = $this->db->conn->prepare($query);
}   
}

然后使用以下命令初始化您的Auth对象:

$aut = new Auth($db);

其中$ db是数据库访问类的实例;