2013-12-17 127 views
0

通常能言善辯模型用於如下:Laravel4:從實例化的類對象調用靜態方法

class Article extends Eloquent 
{ 
// Eloquent Article implementation 
} 

class MyController extends BaseController 
{ 
public function getIndex() 
{ 
    $articles = Article::all(); // call static method 

    return View::make('articles.index')->with('articles', $articles); 
} 
} 

但是改制之使用依賴注入的時候,它看起來就像是:

interface IArticleRepository 
{ 
public function all(); 
} 

class EloquentArticleRepository implements IArticleRepository 
{ 
public function __construct(Eloquent $article) 
{ 
    $this->article = $article; 
} 

public function all() 
{ 
    return $this->article->all(); // call instance method 
} 
} 

那麼,爲什麼我們就可以以實例方法$ this-> article-> all()的形式調用靜態方法Article :: all()?

P/S:抱歉我的英文不好。

+0

變化'公共職能全部()'來'靜態公共職能全部( )' –

回答

2

好問題。

Laravel利用Facade design pattern。當你撥打Article::all()時,屏幕後面發生了很多事情。首先,PHP嘗試調用靜態方法,如果php失敗,立即調用魔術方法_callStatic。然後Laravel巧妙地捕獲static call並創建原始類的實例。

從Laravel DOC:

Facades provide a "static" interface to classes that are available in the application's IoC container. Laravel ships with many facades, and you have probably been using them without even knowing it!

更多信息:

http://laravel.com/docs/facades

http://usman.it/laravel-4-uses-static-not-true/

+0

謝謝你回答我。在我看來,Facade引用了Laravel核心類,而不是用戶創建的Eloquent模型。我瀏覽了Illuminate \ Database \ Eloquent \ Model.php(這是Eloquent別名),並看到all()在這裏被定義爲靜態方法。我錯了嗎? – user3110126

+0

看看這個:http://stackoverflow.com/questions/15070809/creating-a-chainable-method-in-laravel/15182765#15182765 –

相關問題