Luc*_*rez 0 php dependency-injection interface laravel-5
我正在使用 laravel 5.* (而且我也使用 Laravel 4),我不明白为什么注入接口而不是具体类更好。
有什么好处?
我注入接口是因为我读到它好得多,但是我不明白为什么。
谢谢!
首先,这不是 Laravel 特有的东西,它只是被认为是一般的最佳实践。
如果您注入一个具体的类,您就创建了一个硬依赖项。
如果注入接口,则可以使用相同的代码,但只需注入实现相同接口的不同类(例如:用于产品的真实 DB 类,用于测试的模拟 DB 类)。
实际上,您总是注入具体类,这只是类型暗示这是一个接口而不是具体类
例子:
class DB implements DBInterface
{
// A bunch of methods fetching from real DB
}
class MockDB implements DBInterface
{
// Has the same (interface) methods but returns some fixed data for testing.
}
class Posts
{
public function __construct(DBInterface $db)
{
$this->db = $db;
}
public function get()
{
$this->db->query("....");
}
}
$posts = new Posts(new DB);
$data = $posts->get(); // This fetches from the real db
// And for testing
$posts = new Posts(new MockDB);
$data = $posts->get(); // Fetches from the mock DB instead
Run Code Online (Sandbox Code Playgroud)
这样做的强大之处在于,您注入的类将具有相同的类签名,但可以具有完全不同的实现。你的Posts类不需要关心它得到什么实现......
这只是一个简单的示例,但它解释了使用接口作为类型提示的一个非常好的好处......