依赖注入的定义与核心价值
本内容详细解析了PHP中经典的依赖注入设计模式及其具体应用方式,旨在为开发者提供实用的参考范例。
依赖注入的核心在于将类中固定不变的部分与可替换的部分进行分离,借助注入机制来调用依赖,进而达成模块间的解耦效果。
首先定义一个基础的数据库连接类:
class Mysql{
private $host;
private $prot;
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);
}
}
在实际场景中,该类的典型调用方式如下:
$db = new Mysql();
$db->connect();
尽管生产环境中数据库连接类通常需采用单例模式设计,但为了清晰阐述原理,此处暂不引入复杂结构。
依赖注入
鉴于数据库配置信息属于易变部分,我们应将其独立抽取出来:
class MysqlConfiguration{
private $host;
private $prot;
private $username;
private $password;
private $db_name;
public function __construct($host,$port,$username,$password,$db_name){
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
$this->db_name = $db_name;
}
public function getHost(){
return $this->host;
}
public function getPort(){
return $this->port();
}
public function getUsername(){
return $this->username;
}
public function getPassword(){
return $this->password;
}
public function getDbName(){
return $this->db_name;
}
}
随后,处理那些不可替换的核心逻辑部分:
class Mysql{
private $configuration;
public function __construct($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());
}
}
至此,配置文件与连接逻辑的分离工作便已完成。
使用
$config = new MysqlConfiguration('127.0.0.1','root','password','my_db',22);
// $config是注入Mysql的,这就是所谓的依赖注入
$db = new Mysql($config);
$db->connect();
期望上述内容能对各位在PHP程序设计领域的学习与应用有所帮助。