Reputation: 43
I'm trying to access the PDO
object within a class I've created but it throws an error:
Call to undefined method EntelDB::prepare()
Below is the code. How could I access the native PDO
methods like prepare()
and 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();
Upvotes: 1
Views: 292
Reputation: 1769
You are using singleton pattern, but also you want to get "conn" variable as a public property in the Auth class.
Add a constructor to the Auth class:
public function __construct()
{
$this->conn = DB::getInstance()->conn;
}
In the line:
$this->conn= DB::getInstance("patikana","root","");
You are not attaching connection but the DB object instance.
Also consider using dependency injection rather than singleton. Singleton is an antipattern hard to maintain.
I would suggest refactoring:
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);
}
}
Then initialize your Auth object with:
$aut = new Auth($db);
where $db is instance of your Database access class;
Upvotes: 2