Reputation: 497
I usually store PDO object as a member. However, during practice dependency injection, I have a issue that I can't decide an elegant way of handling database connection.
!! What I've done. In every instantiating the class, I always pass PDO object to the constructor. Constructor stores a reference of given PDO object.
class Examples
{
/* Properties */
public $db;
/* Constructor */
public function __construct(PDO &pdo)
{
$this->db = $pdo;
}
//..
}
It works well, even that I'm suffering unknown reason. I'm haunted some bzar doubt, Am I doing right?
The main question is, how can I give database connection to certain class? extend PDO? pass PDO object as parameter? or Make another class extends PDO and implements both? ..??? ??? ???????????? ;OTL
Upvotes: 1
Views: 82
Reputation: 129
You don't need to pass the $pdo as a reference using ampersand, because in PHP the objects are passed by references by default. Your example is fine. Never extend your entity/model class with PDO, unless doing a specialised version of PDO. If you have plenty of classes using $pdo and other services (such as sessions, file system, APIs etc.) then you can think about creating a service manager (container) and then calling it to get the reusable objects, such as your $pdo. In case you will replace PDO with something else in the future, you don't need to rewrite all the classes that are pulling it as an argument.
Upvotes: 1