I used to extend the Db connection class in every class that needs to connect to the database. I think that this is the most common way. But, by following this way, you open and close a new connection in every class instance that extends the db connection class. Lately, i thought that i could create a pdo object and pass it into class' constructor. So, every class instance that needs access to database use the same connection. It works but i am not sure if this is an efficient way to do it. Also, i have a function called closeCon that i call at the end of the script so as to close the connection via null and unset. I would like to know your opinion about that too. Thank you in advance : )
METHOD 1: New class extends dbConnection class.
class Db {
public $pdo;
public function __construct($usr, $pwd, $db) {
$this->pdo = new PDO("mysql:host=localhost;dbname=".$db.";charset=utf8", $usr, $pwd);
}
}
class Users extends Db{
public function __construct(){
parent::__construct($usr, $pwd, $db);
}
}
METHOD 2: Connect to db by passing PDO dbConnection variable into new class' constructor.
class Db {
public $pdo;
public function __construct($usr, $pwd, $db) {
$this->pdo = new PDO("mysql:host=localhost;dbname=".$db.";charset=utf8", $usr, $pwd);
}
public function closeCon(){
$this->pdo = null;
unset($this->pdo);
}
}
class Users {
protected $pdo;
public function __construct($con){
$this->pdo = $con;
}
}
$db = new Db($usr, $pwd, $db);
$posts = new Users($db->pdo);
$db->closeCon();