Answer the question
In order to leave comments, you need to log in
How to pass a database object to a class?
Guys, I'm confused. There is a base App class to which the PDO database object must be passed. I have three solutions, but I’m even confused with the transfer, I don’t understand which one is better (correct), although they all work.
Option 1
class App{
protected $db;
public function __construct(){
$this->db = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
}
}
class App{
protected $db;
public function initDB(PDO $db){
$this->db = $d;
}
}
class DB{
public $db;
public function instance(){
$this->db = new PDO('mysql:host=localhost;dbname=dbname','user','pass');
return $this->db;
}
}
$app = new App();
$db = new DB();
$app->initDB($db->instance());
class App{
protected $db;
public function initDB(PDO $db){
$this->db = $d;
}
}
class DB{
public $db;
public function __construct(){
$this->db = new PDO('mysql:host=localhost;dbname=dbname','user','pass');
}
}
$db = new DB();
$app = new App();
$app->initDB($db);
Answer the question
In order to leave comments, you need to log in
Classic DI
class App{
protected $db;
public function __construct($db){
$this->db = $db;
}
}
Why do you need an extra DB object? If it is needed only to initialize the connection to the database, then you are just wasting memory.
In fact, you've made a wrapper class over PDO. Although in the current implementation, I do not see any need for this.
I would not complicate what works without complication. What for to fence superfluous classes and objects??
Go from need. Need to control connection creation? - do initDB (), you do not need to control, and the object is always created when declaring App (), then the extra class is not needed.
As someone said: "to complicate is easy, to simplify is difficult." Don't make life difficult for yourself
<?
class App{
protected static $_instance;
private function __construct(){
return new PDO('mysql:host=localhost;dbname=dbname','user','pass');
}
# Singlton methods
public static function getInstance()
{
self::$_instance = self::$_instance ?? new self;
return self::$_instance;
}
private function __clone() {}
private function __wakeup() {}
}
# Init
App::getInstance();
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question