PHP: Simple example of Dependency Injection

Dependency Injection is a software-design pattern which is used to remove hard
dependencies from code, and it allows us to change that dependency without
affecting the actual implementation.

 
class Car
{
    function __construct()
    {
    $this->_database = DB::getInstance();
    // OR infamous Global $DB way
    Global $db;
    $this->_database = $db;
    }
}

Here, database is our hard dependency. We have bound the Car class with a
database object. Assume that you want to use the Car class in one of your other
projects and it uses a different database such as MongoDB or MSSQL. So how can we remove this
dependency? Here is the answer:

class Car
{
  private $_database;
  function __construct($dbconnection)
  {
  $this->_database = $dbconnection;
  }

So if you have observed carefully, we are now injecting our database dependency
via constructor. That’s what we call Dependency Injection.

}

Blogbook : PHP | Javascript | Laravel | Corcel | CodeIgniter | VueJs | ReactJs | WordPress