引用Laravel's documentation:
IoC 容器可以通过两种方式解决依赖关系:通过
关闭回调或自动解析。
但首先,什么是依赖项?在您发布的代码中,UserRepository 类有一个依赖项,即Something 类。这意味着UserRepository 将在其代码中的某处依赖Something。而不是直接使用它,通过做这样的事情
$something = new Something;
$something->doSomethingElse();
它在其构造函数中被注入。这种技术被称为 dependency injection。所以,这些代码 sn-ps 会做同样的事情,不管有没有依赖注入。
// 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');
当使用接口作为构造函数的参数时,这特别有用并允许您的类更加灵活。