Laravel4:从实例化的类对象中调用静态方法

时间:2013-12-17 08:05:57

标签: php laravel eloquent

通常使用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
 }
}

那么为什么我们可以以实例方法的形式调用静态方法Article :: all()$ this-> article-> all()?

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

1 个答案:

答案 0 :(得分:2)

好问题。

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/