Laravel 4控制反转

Laravel 4控制反转,laravel,laravel-4,Laravel,Laravel 4,我正在看一段视频,解释laravel的IoC容器的基本原理,我很难理解这段代码在做什么。具体来说,我不理解UserRepository类的构造函数中的参数。我在php站点上没有找到这种语法的示例 引用: IoC容器有两种解决依赖关系的方法:通过 闭包回调或自动解析 但首先,什么是依赖性?在您发布的代码中,UserRepository类有一个依赖项,即Something类。这意味着UserRepository将依赖于其代码中的某个地方。而不是直接使用它,通过这样做 $something = n

我正在看一段视频,解释laravel的IoC容器的基本原理,我很难理解这段代码在做什么。具体来说,我不理解UserRepository类的构造函数中的参数。我在php站点上没有找到这种语法的示例


引用:

IoC容器有两种解决依赖关系的方法:通过 闭包回调或自动解析

但首先,什么是依赖性?在您发布的代码中,
UserRepository
类有一个依赖项,即
Something
类。这意味着
UserRepository
将依赖于其代码中的某个地方。而不是直接使用它,通过这样做

$something = new Something;
$something->doSomethingElse();
它在构造函数中被注入。这种技术称为。因此,这些代码片段在不使用依赖项注入和使用依赖项注入的情况下也会执行相同的操作

// 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();
    }

}
您是说您不理解构造函数中传递的参数
\uu构造函数(Something$Something)
。这一行告诉PHP构造函数需要一个参数,
$something
,它必须是
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是我的第一个!如果所有这些概念现在听起来都很奇怪,不要担心。随着你经验的增加,它们会变得清晰。我们都去过;)
 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');