class Database { protected $adapter; public function __construct(MySqlAdapter $adapter) { $this->adapter = $adapter; //依赖于具体的实例 } } class MysqlAdapter {}
class Database { protected $adapter; public function __construct(AdapterInterface $adapter) { $this->adapter = $adapter; //依赖于抽象 } } interface AdapterInterface {} class MysqlAdapter implements AdapterInterface {}
现在 Database
类依赖于接口,相比依赖于具体实现有更多的优势。
假设你工作的团队中,一位同事负责设计适配器。在第一个例子中,我们需要等待适配器设计完之后才能单元测试。现在由于依赖是一个接口/约定,我们能轻松地模拟接口测试,因为我们知道同事会基于约定实现那个适配器
这种方法的一个更大的好处是代码扩展性变得更高。如果一年之后我们决定要迁移到一种不同的数据库,我们只需要写一个实现相应接口的适配器并且注入进去,由于适配器遵循接口的约定,我们不需要额外的重构。
引自:http://laravel-china.github.io/php-the-right-way/#dependency_injection
原文:https://www.cnblogs.com/bneglect/p/12492199.html