Dependency Injection In Php

Dependency Injection(DI) is a part of software design.  DI is a procedure for managing object dependencies with another object so it will eliminate hard-coding dependencies for a class object. Using DI, we can change dependencies in runtime and compile time.

Lets see , what is mean by DI.

1. First Case:  class dependencies without DI

Suppose an application have class A, class B and class C. Now class A needs class B and class B needs class class C so in this we will create separate objects. In class A, we will create object of class B. In class B, we will create object of class C. In this application, class A dependent on class B object and class B dependent on class C object.

In one line: Application needs A, which needs B, which needs C

Example: Now understand it by an example

Suppose we want to get all users from DB so we will need two classes: class DB and class User and Same for Post class


class User
{
   private $DB = null;

   public function __construct() {
     $this->DB = new Db('host', 'user', 'pass', 'dbname');
   }

   public function getAllUsers() {
     return $this->DB->getAll('users');
   }
}

class Post
{
   private $DB = null;

   public function __construct() {
     $this->DB = new Db('host', 'user', 'pass', 'dbname');
   }

   public function getAllPosts() {
    return $this->getAll('posts');
   }
}

$post = new Post();
$post->getAllPosts();

/* Suppose we want to change DB details then we will need to change in both class User and 
Post for DB details but we can solve this issue by using DI */

 

2. Second Case: class dependencies with DI 

We can Implement DI by two ways

1. Constructor Injection – In Constructor Injection, we can inject an object through the class constructor.


class User
{
  private $DB = null;

  public function __construct(Db $db) {
    $this->DB = $db;
  }

  public function getUsers() {
   return $this->getAll('users');
  }
}

$db = new Db('host', 'user', 'pass', 'dbname');
$user = new User($db); // Injecting
$user->getUsers();

2. Setter Injection – Injecting the object to class through a setter function.


class User 
{
    private $DB = null;

    public function setDb(Db $Db) {
        $this->DB = $Db;
    }

    public function getUsers() {
        return $this->DB->getAll('users');
    }
}

$db = new Db('host', 'user', 'pass', 'dbname');
$user = new User();
$user->setDb($db);
$user->getUsers();

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Follow by Email
LinkedIn
Share
Instagram