1

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

3 Answers3

1

There is absolutely no point in extending application classes from DB class. So - Plan B.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

The only case Method 1 might be acceptable is if Users were a model. However, this approach is typically bad practice due to coupling, multiple inheritance limitations, etc. And in your case creates multiple database connections.

Method 2, is a better approach of the two. It is a form of dependency injection.

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
-2

Good work. This is much more efficient than opening a connection every time, and you are properly disposing of your connections when you are done.

Lyn Headley
  • 11,368
  • 3
  • 33
  • 35