I currently have a database wrapper that uses a Singleton, like so:
class Database {
private static $db;
public static function getInstance() {
if(!self::$db) {
self::$db = new PDO();
}
return self::$db;
}
}
I also have a User class that has a few methods I want to call statically, but they require a database connection, which I’m doing like so:
class User {
private static $db;
public function __construct() {
self::$db = Database::getInstance();
}
public static function someMethod() {
self::$db->someQuery();
}
}
User::someMethod();
My question is, how would I accomplish the same thing using Dependency Injection instead of Singleton, without making multiple DB connections?
You would simply pass the DB connection to the constructor like this: