Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO objects across classes

I'm looking for some feedback on the following:

I currently have two classes, which are being used in my PHP application.

A database connection class, which is currently using MySQL (but switching to PDO).

Another class (with several functions) which requires database functionality.

I'm looking for the best way to design this, I've read up on singletons (with very mixed reviews), read examples where objects were simply declared as new for each method (class functions), and examples where the connection was assigned to a private variable as part of a __constructor method for each class (then referenced with $this->).

So, how does everyone else do it? I hope you will be kind enough to perhaps give an example, and also welcome opinions on what others have read please.

I've got 2 separate classes, in two separate files. I want to keep clean code, reduce unnecessary overhead on the DB, and avoid anything that could be considered outdated (such as globals).

like image 577
Craig Wilson Avatar asked Jan 26 '26 01:01

Craig Wilson


1 Answers

The Database class, which is responsible for connecting, should be the one connecting to the database, creating the new PDO instance, and saving it to a field in itself.

class Database {
    private $pdo;
    public __construct() {
        $this->pdo = new PDO(...);
    }
}

The second class, which doesn't care where the DB connection is from, it just needs it to work should be injected with the Database class:

class WorkerClass {
    private $db;
    public __construct(Database $db) {
        $this->db = $db;
    }
}
like image 83
Madara's Ghost Avatar answered Jan 27 '26 14:01

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!