2013-11-24 39 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