Home >Backend Development >PHP Tutorial >PHP design pattern-detailed explanation of the use of dependency injection
Preface
Finally let’s talk about this famous Design Principle. In fact, it is simpler than other Design Patterns.
The essence of dependency injection is to separate the irreplaceable parts of a class from the replaceable parts and use them through injection to achieve the purpose of decoupling.
Here is an example of a database link. I hope everyone understands that
class Mysql{ private $host; private $port; private $username; private $password; private $db_name; public function construct(){ $this->host = '127.0.0.1'; $this->port = 22; $this->username = 'root'; $this->password = ''; $this->db_name = 'my_db'; } public function connect(){ return mysqli_connect($this->host,$this->username ,$this->password,$this->db_name,$this->port); } }
Used
$db = new Mysql(); $con = $db->connect();
should usually be designed as a singleton. Let’s not get too complicated here.
Obviously, the database configuration is a replaceable part, so we need to take it out.
class MysqlConfiguration { private $host; private $port; private $username; private $password; private $db_name; public function construct(string $host, int $port, string $username, string $password,string $db_name) { $this->host = $host; $this->port = $port; $this->username = $username; $this->password = $password; $this->db_name = $db_name; } public function getHost(): string { return $this->host; } public function getPort(): int { return $this->port; } public function getUsername(): string { return $this->username; } public function getPassword(): string { return $this->password; } public function getDbName(): string { return $this->db_name; } }
Then the irreplaceable part is like this:
class Mysql { private $configuration; public function construct(DatabaseConfiguration $config) { $this->configuration = $config; } public function connect(){ return mysqli_connect($this->configuration->getHost(),$this->configuration->getUsername() , $this->configuration->getPassword,$this->configuration->getDbName(),$this->configuration->getPort()); } }
This completes the separation of configuration file and connection logic.
$config = new MysqlConfiguration('127.0.0.1','root','','my_db',22); $db = new Mysql($config); $con = $db->connect();
$config is injected into Mysql, which is called dependency injection.
The above is the detailed content of PHP design pattern-detailed explanation of the use of dependency injection. For more information, please follow other related articles on the PHP Chinese website!