title: Connecting to the MySQL Database using Dependency Injection in PHP
body: <p>I am currently trying to grasp the basics of Dependency Injection and I'm running into quite a bit of trouble.</p>
  
  <p>While I do understand the basic premise of why it's useful (ease of unit testing, removal of hard-coded classes), I don't really understand how that goes into databases.</p>
  
  <p>Basically, I cannot for the life of me understand how I can connect to a database using the DI technique.</p>
  
  <p>As far as I understand I would have to pass all variables through a constructor</p>
  
  <pre><code>Class DatabaseConfiguration
  {
      private $servername;
      private $dbname;
      private $dbuser;
      private $dbpass;
  
      public function __construct(string $server, string $name, string $user, 
      string $pass, string $charset){
          $this-&gt;servername = $server;
          $this-&gt;dbname = $name;
          $this-&gt;dbuser = $user;
          $this-&gt;dbpass = $pass;
          $this-&gt;dbcharset = $charset;
  }
  </code></pre>
  
  <p>This is where I get stuck. I am quite clueless on what I should be doing next to establish a connection.</p>
  
  <p>Usually, I would hard-code the values and then call a function in which I would do something like this:</p>
  
  <pre><code>public function connectDB(){
      try{
          $conn = "mysql:host=".$this-&gt;servername.";dbname=".$this-&gt;dbname.";charset=".$this-&gt;dbcharset;
          $pdo = new PDO($conn, $this-&gt;dbuser, $this-&gt;dbpass);
          $pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          return $pdo;
      }catch(PDOException $e){
          echo "Connection failed: ".$e-&gt;getMessage();
      }
  }
  </code></pre>
  
  <p>I have no clue how to do it the DI way, though.</p>