sajad torkamani

In a nutshell

A “facade” is a static “proxy”/interface to a class available in the application’s service container. They provide a terse syntax for accessing underlying classes in the service container.

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

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

Create a facade

A facade extends the Illuminate\Support\Facades\Facade class and defines a single static getFacadeAccessor() method:

class Cache extends Facade
{
    /**
     * Get the registered name of the component.
     */
    protected static function getFacadeAccessor(): string
    {
        return 'cache';
    }
}

For example, if you call the Cache facade like this:

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;
 
class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     */
    public function showProfile(string $id): View
    {
        $user = Cache::get('user:'.$id);
 
        return view('profile', ['user' => $user]);
    }
}

Then when a user references any static method on the Cache facade, Laravel will look at the Cache classes’s getFacadeAccessor() class to retrieving the underlying service from the service container and execute the requested method (in this case, get) against that object.

Laravel facades reference list

See here.

When to use facades

Facades provide a terse syntax to using services without needing to inject them as dependencies.

The main danger with facades is “scope screep” which is that a class may end up using many facades and growing too big. If you use dependency injection, the large list of dependencies in your constructor will show the scope creep whereas with facades, the scope creep can be harder to identify.

Sources/further reading

Tagged: Laravel