PHP依赖注入简单理解

来源:互联网 发布:windows 10 修复bcd 编辑:程序博客网 时间:2024/05/24 06:55
<?php//依赖注入(Dependency injection)也叫控制反转(Inversion of Control)是一种设计模式//这种模式用来减少程序间的耦合。//假设我们有个类,需要用到数据库连接,我们可能这样写class UseDataBase{protected $adapter;public function __construct(){$this->adapter=new MySqlAdapter;}public function getList(){$this->adapter->query("sql语句");//使用MySslAdapter类中的query方法;}}class MySqlAdapter{};//我们可以通过依赖注入来重构上面这个例子class UseDataBase{protected $adapter;poublic function __construct(MySqlAdapter $adapter){$this->adapter=$adapter;}public function getList(){$this->adapter->query("sql语句");//使用MySslAdapter类中的query方法;}}class MySqlAdapter{};//但是,当我们有很多种数据库时,上面的这种方式就达不到要求或者要写很多个usedatabase类//所以我们再重构上面的这个例子class UseDataBase{protected $adapter;poublic function __construct(AdapterInterface $adapter){$this->adapter=$adapter;}public function getList(){$this->adapter->query("sql语句");//使用MySslAdapter类中的query方法;}}interface AdapterInterface{};class MySqlAdapter implements AdapterInterface{};class MSsqlAdapter implements AdapterInterface{};//这样的话,当要使用不同的数据库时,我们只需要添加数据库类就够了,usedatabase类则不需要动。?>

0 0