M
M
Max Ba2019-01-28 11:43:22
PHP
Max Ba, 2019-01-28 11:43:22

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');
  }
}

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

Option 3
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

4 answer(s)
T
ThunderCat, 2019-01-28
@ThunderCat

Classic DI

class App{
  protected $db;
  public function __construct($db){
    $this->db = $db;
  }
}

A
Arthur K., 2019-01-28
@amark

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

P
Pavel Kornilov, 2019-01-28
@KorniloFF

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

lifeexample.ru/php-primeryi-skriptov/php-singleton...

H
hack504, 2019-01-28
@hack504

Option 2 is needed if an instance of the DB class will be used somewhere else besides App. And also, if the classes are slightly corrected, then you can make a LazyLoad connection to the database in the App class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question