Simple Explanation of Dependency Injection

Nguyen Hoang - Aug 27 - - Dev Community

Dependency Injection is a way to provide:

  • component
  • services to a class class dont need to create these:
  • component
  • services

Without DI:
`class UserService {
private $db;

public function __construct() {
    $this->db = new DatabaseConnection(); // The class creates its own dependency
}
Enter fullscreen mode Exit fullscreen mode

}`

With DI:

`class UserService {
private $db;

// Dependency is injected
public function __construct(DatabaseConnection $db) {
    $this->db = $db;
}
Enter fullscreen mode Exit fullscreen mode

}

// Creating the dependency and injecting it
$db = new DatabaseConnection();
$userService = new UserService($db);`

In this DI example:

  • The UserService class does not need to know how to create a DatabaseConnection; it just uses it.
  • This makes it easier to switch out DatabaseConnection for another implementation or a mock during testing, because the class is decoupled from the specific way the connection is created.

. Constructor Injection
Setter Injection

Setter Injection sử dụng các phương thức setter để cung cấp phụ thuộc cho đối tượng. Phụ thuộc có thể được thay đổi sau khi đối tượng đã được tạo ra. Điều này có thể hữu ích khi một số phụ thuộc không phải là bắt buộc, hoặc khi chúng có thể thay đổi trong quá trình sống của đối tượng.

Interface Injection

. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player