报价Laravel's documentation:
有两种方式IoC容器可以解决依赖关系:通过 关闭回调或自动解决。
但首先,什么是依赖?在您发布的代码中,UserRepository
类具有一个依赖项,即Something
类。这意味着UserRepository
将取决于Something
其代码中的某处。而不是直接使用它,通过做这样的事情
$something = new Something;
$something->doSomethingElse();
是在其构造函数被注入。这种技术被称为dependency injection。所以,这些代码片段将会执行相同的操作,无需依赖注入。
// Without DI
class UserRepository {
public function doSomething()
{
$something = new Something();
return $something->doSomethingElse();
}
}
现在,使用DI,这将是一样的,你贴:
// With DI
class UserRepository {
public function __construct(Something $something)
{
$this->something = $something;
}
public function doSomething()
{
return $this->something->doSomethingElse();
}
}
你是说你不明白在构造__constructor(Something $something)
传递的参数。该行告诉PHP构造函数需要一个参数$something
,其中必须是Something
类的实例。这被称为type hinting。传递不是Something
(或任何子类)实例的参数将引发异常。
最后,让我们回到IoC容器。我们之前已经说过它的功能是解决依赖关系,它可以通过两种方式来实现。
首先一个,关闭回调:
// This is telling Laravel that whenever we do
// App::make('user.repository'), it must return whatever
// we are returning in this function
App::bind('UserRepository', function($app)
{
return new UserRepository(new Something);
});
第二个,自动解析
class UserRepository {
protected $something;
public function __construct(Something $something)
{
$this->something = $something;
}
}
// Now when we do this
// Laravel will be smart enough to create the constructor
// parameter for you, in this case, a new Something instance
$userRepo = App::make('UserRepository');
这是特别有帮助,并允许你的类更灵活,使用接口为您的构造函数的参数时, 。
很好的解释!我一直在阅读这篇文章,试图了解它是如何工作的。这现在更有意义了......我还是PHP框架的新手,laravel是我的第一个! –
如果所有这些概念现在听起来很奇怪,别担心。随着你更有经验,他们会变得清晰。我们一直在那里;) –
+1的很好的解释。 :) – itachi