簡體   English   中英

Laravel4:從實例化的類對象中調用靜態方法

[英]Laravel4: call static method from instantiated class object

通常,Eloquent模型使用如下:

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:抱歉我的英語不好。

好問題。

Laravel采用Facade design pattern 當你調用Article::all() ,屏幕后面發生了很多事情。 首先,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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM