2013-11-24 32 views
4

我正在观看解释laravel的IoC容器的基础知识的视频,我无法理解此代码正在做什么。具体来说,我不明白UserRepository类的构造函数中的参数。我没有太多的运气在php网站上找到这个语法的例子。Laravel 4控制反转

http://vimeo.com/53009943

<?php 

class UserRepository { 

    protected $something; 

    public function __construct(Something $something) 

    { 

     $this->something = $something; 

    } 
} 

class Something {} 

?> 

回答

8

报价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'); 

这是特别有帮助,并允许你的类更灵活,使用接口为您的构造函数的参数时, 。

+0

很好的解释!我一直在阅读这篇文章,试图了解它是如何工作的。这现在更有意义了......我还是PHP框架的新手,laravel是我的第一个! –

+1

如果所有这些概念现在听起来很奇怪,别担心。随着你更有经验,他们会变得清晰。我们一直在那里;) –

+0

+1的很好的解释。 :) – itachi