Facades

    Facades provide a "static" interface to classes that are available in the application's . 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 namespace. So, we can easily access a facade like so:

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

    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.

    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:

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

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

    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.

    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 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 and runs the requested method (in this case, get) against that object.

    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. *
    9. * @param Publisher $publisher
    10. * @return void
    11. */
    12. public function publish(Publisher $publisher)
    13. {
    14. $this->update(['publishing' => now()]);
    15. $publisher->publish($this);
    16. }
    17. }

    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:

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