2.9. 依赖注入模式(Dependency Injection)
前言
我觉得:
依赖注入 依赖的应该是一个抽象的类,而不是一个具体的类。
代码差不多都是适配器模式的代码。
正确例子
<?php
//数据库适配器 必须实现这些接口
interface SqlAdapterInterface
{
public function connection();
}
class Mysql implements SqlAdapterInterface
{
public function connection()
{
echo 'mysql连接成功'.PHP_EOL;
}
}
class SqlServer implements SqlAdapterInterface
{
public function connection()
{
echo 'sqlServer连接成功'.PHP_EOL;
}
}
class Database
{
protected $sql;
//限定对象是SqlAdapterInterface 这个是抽象的
public function __construct(SqlAdapterInterface $sql)
{
$this->sql = $sql;
}
}
$sql = new Mysql();
//$sql = new SqlServer();
//依赖SqlAdapterInterface 并注入
new Database($sql);
失败例子
class Database
{
protected $sql;
//都限定必须是Mysql了 这跟我new Mysql有区别吗?
//如果你是在lar用这种写法 我觉得并不算真正的依赖注入
public function __construct(Mysql $sql)
{
$this->sql = $sql;
}
}