温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在PHP中定义依赖注入

发布时间:2021-05-10 17:22:03 来源:亿速云 阅读:113 作者:Leah 栏目:开发技术

本篇文章为大家展示了怎么在PHP中定义依赖注入,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

php是什么语言

php,一个嵌套的缩写名称,是英文超级文本预处理语言(PHP:Hypertext Preprocessor)的缩写。PHP 是一种 HTML 内嵌式的语言,PHP与微软的ASP颇有几分相似,都是一种在服务器端执行的嵌入HTML文档的脚本语言,语言的风格有类似于C语言,现在被很多的网站编程人员广泛的运用。

一个数据库连接类:

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中定义依赖注入,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI