user3110126
user3110126

Reputation: 1

Laravel4: call static method from instantiated class object

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.

Upvotes: 0

Views: 1241

Answers (1)

Anam
Anam

Reputation: 12169

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/

Upvotes: 2

Related Questions