Dependency injection và dependency injection container trong Laravel

Image for post
Image for post

Định nghĩa

Lợi ích

Nhược điểm

Ví dụ

class Config {
private $username;
private $password;
public function __construct($username, $password) {
$this->username = $username;
$this->password = $password;
}
public function getUsername(): string
{
return $this->username;
}
public function getPassword(): string
{
return $this->password;
}
}
// C1. Không sử dụng DI
class Database
{
private $config;
public function __construct($username, $password) {
$this->config = new Config($username, $password);
}
public function getConfig() {
return $this->config;
}
}
$database = new Database('buihuycuong', 'ratdeptrai');
var_dump($database->getConfig());
// C2. Sử dụng DI
class Database
{
private $config;
public function __construct(Config $config) {
$this->config = $config;
}
public function getConfig() {
return $this->config;
}
}
$config = new Config('buihuycuong', 'ratdeptrai');
$database = new Database($config);
var_dump($database->getConfig());
// C3. Sử dụng DI trong setter
class Database
{
private $config;
public function __construct() {
}
public function getConfig() {
return $this->config;
}
public function setConfig(Config $config) {
$this->config = $config;
}
}
$config = new Config('buihuycuong', 'ratdeptrai');
$database = new Database();
$database->setConfig($config);
var_dump($database->getConfig());
// C4. Sử dụng DI thông qua Interfaceinterface DatabaseInterface {
public function getConfig();
public function setConfig(Config $config);
}

Các kiểu Dependency Injection

Dependency Injection Container

Written by

Be Curious!| ☕️+✍🏼=❤️ | buihuycuong.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store