1

I read about Facade Pattern

The facade pattern (also spelled façade) is a software design pattern commonly used with object-oriented programming. The name is an analogy to an architectural façade. A facade is an object that provides a simplified interface to a larger body of code, such as a class library.

But in Laravel all the Facade Classes methods are accessed via the ::(Scope Resolution Operator) even though the methods are not static at all.

How is this possible? Why PHP is not telling that the method is not static.

for example Auth::user() eventhough the user() method is not static how is is accessible, somewhere the class should be newed up or am I missing something?

Shobi
  • 10,374
  • 6
  • 46
  • 82

1 Answers1

4

The magic happens in Facade's __callStatic function.

public static function __callStatic($method, $args)
{
    $instance = static::getFacadeRoot();
    if (! $instance) {
        throw new RuntimeException('A facade root has not been set.');
    }
    return $instance->$method(...$args);
}

It first gets the appropriate instance, and then simply invokes the requested method with the given arguments.

Emile Pels
  • 3,837
  • 1
  • 15
  • 23
  • where do the instances are stored then? – Shobi Feb 16 '18 at 16:30
  • @ShobiPP Please check the source I have linked. `Facade` is an abstract class that is implemented by types like `Auth` and `DB`. Those can all be found in `Illuminate\Support\Facades`: https://github.com/laravel/framework/tree/5.6/src/Illuminate/Support/Facades – Emile Pels Feb 16 '18 at 16:32