Facades

Introduction

Facades provide a "static" interface to classes that are available in the application's service container. Laravel ships with many facades which provide access to almost all of Laravel's features. Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

All of Laravel's facades are defined in the Illuminate\Support\Facades namespace. So, we can easily access a facade like so:

  1. use Illuminate\Support\Facades\Cache;
  2. Route::get('/cache', function () {
  3. return Cache::get('key');
  4. });

Throughout the Laravel documentation, many of the examples will use facades to demonstrate various features of the framework.

When To Use Facades

Facades have many benefits. They provide a terse, memorable syntax that allows you to use Laravel's features without remembering long class names that must be injected or configured manually. Furthermore, because of their unique usage of PHP's dynamic methods, they are easy to test.

However, some care must be taken when using facades. The primary danger of facades is class scope creep. Since facades are so easy to use and do not require injection, it can be easy to let your classes continue to grow and use many facades in a single class. Using dependency injection, this potential is mitigated by the visual feedback a large constructor gives you that your class is growing too large. So, when using facades, pay special attention to the size of your class so that its scope of responsibility stays narrow.

{tip} When building a third-party package that interacts with Laravel, it's better to inject Laravel contracts instead of using facades. Since packages are built outside of Laravel itself, you will not have access to Laravel's facade testing helpers.

Facades Vs. Dependency Injection

One of the primary benefits of dependency injection is the ability to swap implementations of the injected class. This is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub.

Typically, it would not be possible to mock or stub a truly static class method. However, since facades use dynamic methods to proxy method calls to objects resolved from the service container, we actually can test facades just as we would test an injected class instance. For example, given the following route:

  1. use Illuminate\Support\Facades\Cache;
  2. Route::get('/cache', function () {
  3. return Cache::get('key');
  4. });

We can write the following test to verify that the Cache::get method was called with the argument we expected:

  1. use Illuminate\Support\Facades\Cache;
  2. /**
  3. * A basic functional test example.
  4. *
  5. * @return void
  6. */
  7. public function testBasicExample()
  8. {
  9. Cache::shouldReceive('get')
  10. ->with('key')
  11. ->andReturn('value');
  12. $this->visit('/cache')
  13. ->see('value');
  14. }

Facades Vs. Helper Functions

In addition to facades, Laravel includes a variety of "helper" functions which can perform common tasks like generating views, firing events, dispatching jobs, or sending HTTP responses. Many of these helper functions perform the same function as a corresponding facade. For example, this facade call and helper call are equivalent:

  1. return View::make('profile');
  2. return view('profile');

There is absolutely no practical difference between facades and helper functions. When using helper functions, you may still test them exactly as you would the corresponding facade. For example, given the following route:

  1. Route::get('/cache', function () {
  2. return cache('key');
  3. });

Under the hood, the cache helper is going to call the get method on the class underlying the Cache facade. So, even though we are using the helper function, we can write the following test to verify that the method was called with the argument we expected:

  1. use Illuminate\Support\Facades\Cache;
  2. /**
  3. * A basic functional test example.
  4. *
  5. * @return void
  6. */
  7. public function testBasicExample()
  8. {
  9. Cache::shouldReceive('get')
  10. ->with('key')
  11. ->andReturn('value');
  12. $this->visit('/cache')
  13. ->see('value');
  14. }

How Facades Work

In a Laravel application, a facade is a class that provides access to an object from the container. The machinery that makes this work is in the Facade class. Laravel's facades, and any custom facades you create, will extend the base Illuminate\Support\Facades\Facade class.

The Facade base class makes use of the __callStatic() magic-method to defer calls from your facade to an object resolved from the container. In the example below, a call is made to the Laravel cache system. By glancing at this code, one might assume that the static method get is being called on the Cache class:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Support\Facades\Cache;
  5. class UserController extends Controller
  6. {
  7. /**
  8. * Show the profile for the given user.
  9. *
  10. * @param int $id
  11. * @return Response
  12. */
  13. public function showProfile($id)
  14. {
  15. $user = Cache::get('user:'.$id);
  16. return view('profile', ['user' => $user]);
  17. }
  18. }

Notice that near the top of the file we are "importing" the Cache facade. This facade serves as a proxy to accessing the underlying implementation of the Illuminate\Contracts\Cache\Factory interface. Any calls we make using the facade will be passed to the underlying instance of Laravel's cache service.

If we look at that Illuminate\Support\Facades\Cache class, you'll see that there is no static method get:

  1. class Cache extends Facade
  2. {
  3. /**
  4. * Get the registered name of the component.
  5. *
  6. * @return string
  7. */
  8. protected static function getFacadeAccessor() { return 'cache'; }
  9. }

Instead, the Cache facade extends the base Facade class and defines the method getFacadeAccessor(). This method's job is to return the name of a service container binding. When a user references any static method on the Cache facade, Laravel resolves the cache binding from the service container and runs the requested method (in this case, get) against that object.

Real-Time Facades

Using real-time facades, you may treat any class in your application as if it were a facade. To illustrate how this can be used, let's examine an alternative. For example, let's assume our Podcast model has a publish method. However, in order to publish the podcast, we need to inject a Publisher instance:

  1. <?php
  2. namespace App;
  3. use App\Contracts\Publisher;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Podcast extends Model
  6. {
  7. /**
  8. * Publish the podcast.
  9. *
  10. * @param Publisher $publisher
  11. * @return void
  12. */
  13. public function publish(Publisher $publisher)
  14. {
  15. $this->update(['publishing' => now()]);
  16. $publisher->publish($this);
  17. }
  18. }

Injecting a publisher implementation into the method allows us to easily test the method in isolation since we can mock the injected publisher. However, it requires us to always pass a publisher instance each time we call the publish method. Using real-time facades, we can maintain the same testability while not being required to explicitly pass a Publisher instance. To generate a real-time facade, prefix the namespace of the imported class with Facades:

  1. <?php
  2. namespace App;
  3. use Facades\App\Contracts\Publisher;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Podcast extends Model
  6. {
  7. /**
  8. * Publish the podcast.
  9. *
  10. * @return void
  11. */
  12. public function publish()
  13. {
  14. $this->update(['publishing' => now()]);
  15. Publisher::publish($this);
  16. }
  17. }

When the real-time facade is used, the publisher implementation will be resolved out of the service container using the portion of the interface or class name that appears after the Facades prefix. When testing, we can use Laravel's built-in facade testing helpers to mock this method call:

  1. <?php
  2. namespace Tests\Feature;
  3. use App\Podcast;
  4. use Tests\TestCase;
  5. use Facades\App\Contracts\Publisher;
  6. use Illuminate\Foundation\Testing\RefreshDatabase;
  7. class PodcastTest extends TestCase
  8. {
  9. use RefreshDatabase;
  10. /**
  11. * A test example.
  12. *
  13. * @return void
  14. */
  15. public function test_podcast_can_be_published()
  16. {
  17. $podcast = factory(Podcast::class)->create();
  18. Publisher::shouldReceive('publish')->once()->with($podcast);
  19. $podcast->publish();
  20. }
  21. }

Facade Class Reference

Below you will find every facade and its underlying class. This is a useful tool for quickly digging into the API documentation for a given facade root. The service container binding key is also included where applicable.

FacadeClassService Container Binding
AppIlluminate\Foundation\Applicationapp
ArtisanIlluminate\Contracts\Console\Kernelartisan
AuthIlluminate\Auth\AuthManagerauth
Auth (Instance)Illuminate\Contracts\Auth\Guardauth.driver
BladeIlluminate\View\Compilers\BladeCompilerblade.compiler
BroadcastIlluminate\Contracts\Broadcasting\Factory
Broadcast (Instance)Illuminate\Contracts\Broadcasting\Broadcaster
BusIlluminate\Contracts\Bus\Dispatcher
CacheIlluminate\Cache\CacheManagercache
Cache (Instance)Illuminate\Cache\Repositorycache.store
ConfigIlluminate\Config\Repositoryconfig
CookieIlluminate\Cookie\CookieJarcookie
CryptIlluminate\Encryption\Encrypterencrypter
DBIlluminate\Database\DatabaseManagerdb
DB (Instance)Illuminate\Database\Connectiondb.connection
EventIlluminate\Events\Dispatcherevents
FileIlluminate\Filesystem\Filesystemfiles
GateIlluminate\Contracts\Auth\Access\Gate
HashIlluminate\Contracts\Hashing\Hasherhash
LangIlluminate\Translation\Translatortranslator
LogIlluminate\Log\Writerlog
MailIlluminate\Mail\Mailermailer
NotificationIlluminate\Notifications\ChannelManager
PasswordIlluminate\Auth\Passwords\PasswordBrokerManagerauth.password
Password (Instance)Illuminate\Auth\Passwords\PasswordBrokerauth.password.broker
QueueIlluminate\Queue\QueueManagerqueue
Queue (Instance)Illuminate\Contracts\Queue\Queuequeue.connection
Queue (Base Class)Illuminate\Queue\Queue
RedirectIlluminate\Routing\Redirectorredirect
RedisIlluminate\Redis\RedisManagerredis
Redis (Instance)Illuminate\Redis\Connections\Connectionredis.connection
RequestIlluminate\Http\Requestrequest
ResponseIlluminate\Contracts\Routing\ResponseFactory
Response (Instance)Illuminate\Http\Response
RouteIlluminate\Routing\Routerrouter
SchemaIlluminate\Database\Schema\Builder
SessionIlluminate\Session\SessionManagersession
Session (Instance)Illuminate\Session\Storesession.store
StorageIlluminate\Filesystem\FilesystemManagerfilesystem
Storage (Instance)Illuminate\Contracts\Filesystem\Filesystemfilesystem.disk
URLIlluminate\Routing\UrlGeneratorurl
ValidatorIlluminate\Validation\Factoryvalidator
Validator (Instance)Illuminate\Validation\Validator
ViewIlluminate\View\Factoryview
View (Instance)Illuminate\View\View