0

Normally Eloquent model is used as following:

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);
 }
}

But when restructing use Dependency Injection, it looks like that:

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
 }
}

So why we can call the static method Article::all() in form of instance method $this->article->all()?

P/S: Sorry for my bad English.

1 Answers1

2

Good question.

Laravel utilize the Facade design pattern. when you call Article::all(), a lot of things happened behind the screen. First, PHP try to call the static method if it fails php immediately call a magic method _callStatic. then Laravel cleverly capture the static call and create instance of the original class.

From 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!

More info:

http://laravel.com/docs/facades

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

Anam
  • 11,999
  • 9
  • 49
  • 63
  • Thanks for answer me. In my opinion, Facade references to Laravel core class, not user created Eloquent models. I skimmed at Illuminate\Database\Eloquent\Model.php (which is Eloquent alias) and saw that all() is defined here as static method. Am I wrong? – user3110126 Dec 17 '13 at 08:54
  • Take a look at this: http://stackoverflow.com/questions/15070809/creating-a-chainable-method-in-laravel/15182765#15182765 – Manuel Pedrera Dec 17 '13 at 10:33