I am building my own MVC and I have a couple questions about making a database connection and what is the best practice. I have a model User
which interacts with the database and I wonder what is the best practice to instantiate the database connection class. Currently I made it so my User
class extends the Database
class because I don't feel like instantiating it in a constructor for example.
class User extends Database
{
public function data($userid)
{
$getRow = $this->getConnect()->getRow("SELECT * FROM users WHERE userid = ?", [$userid]);
return $getRow;
}
}
And my Database class:
class Database
{
private $dbh = NULL;
private $instance = NULL;
public function __construct($username = 'root', $password = '', $host = '127.0.0.1', $dbname = 'testdb', $options = [])
{
try {
$this->dbh = new PDO("mysql:dbname={$dbname};host={$host};charset=utf8", $username, $password);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
} catch (PDOException $ex) {
throw new Exception($ex->getMessage());
}
}
public function getConnect()
{
if($this->instance == NULL)
{
$this->instance = new self();
}
return $this->instance;
}
}
Also, my getConnect
method seems kinda hard coding. Do you think there is a smarter way to do this?
And one more thing, about public/private if anything is better to be private, I'd appreciate if you let me know.