Facades

Introducción

Facades provide a "static" interface to classes that are available in the application's service container. Laravel incluye muchas facades, ¡y probablemente las has utilizado sin siquiera saberlo! Las "fachadas" de Laravel sirven como un "proxy estático" para clases subyacentes en el service container, proporcionando el beneficio de una sintaxis concisa y expresiva, manteniendo mayor testabilidad y flexibilidad que los métodos estáticos tradicionales.

Using Facades

En el contexto de una aplicación Laravel, una facade es una clase que provee acceso a un objecto desde el contenedor. El mecanismo que hace que esto funcione es la clase Facade. Laravel's facades, and any custom facades you create, will extend the base Illuminate\Support\Facades\Facade class.

A facade class only needs to implement a single method: getFacadeAccessor. Es el trabajo del método getFacadeAccessor definir que resolver desde el contenedor. La clase base Facade utiliza el método mágico __callStatic() para diferir las llamadas desde tu facade para resolver el objeto.

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:

<?php

namespace App\Http\Controllers;

use Cache;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        $user = Cache::get('user:'.$id');

        return view('profile', ['user' => $user]);
    }
}

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:

class Cache extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'cache'; }

}

Instead, the Cache facade extends the base Facade class and defines the method getFacadeAccessor(). Remember, 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.

Referencia de la clase Facade

A continuación encontrarás cada fachada y su clase subyacente. Esta es una herramienta útil para investigar rápidamente la documentación de la API. The service container binding key is also included where applicable.

Fachada Clase Service Container Binding
App Illuminate\Foundation\Application app
Artisan Illuminate\Console\Application artisan
Auth Illuminate\Auth\AuthManager auth
Auth (Instancia) Illuminate\Auth\Guard
Blade Illuminate\View\Compilers\BladeCompiler blade.compiler
Bus Illuminate\Contracts\Bus\Dispatcher
Caché Illuminate\Cache\Repository cache
Config Illuminate\Config\Repository config
Cookie Illuminate\Cookie\CookieJar cookie
Crypt Illuminate\Encryption\Encrypter encrypter
DB Illuminate\Database\DatabaseManager db
DB (Instancia) Illuminate\Database\Connection
Event Illuminate\Events\Dispatcher events
File Illuminate\Filesystem\Filesystem files
Hash Illuminate\Contracts\Hashing\Hasher hash
Input Illuminate\Http\Request request
Lang Illuminate\Translation\Translator translator
Log Illuminate\Log\Writer log
Correo Illuminate\Mail\Mailer mailer
Password Illuminate\Auth\Passwords\PasswordBroker auth.password
Queue Illuminate\Queue\QueueManager queue
Queue (Instancia) Illuminate\Queue\QueueInterface
Queue (Clase base) Illuminate\Queue\Queue
Redirect Illuminate\Routing\Redirector redirect
Redis Illuminate\Redis\Database redis
Request Illuminate\Http\Request request
Response Illuminate\Contracts\Routing\ResponseFactory
Route Illuminate\Routing\Router router
Schema Illuminate\Database\Schema\Blueprint
Sesiones Illuminate\Session\SessionManager session
Session (Instancia) Illuminate\Session\Store
Storage Illuminate\Contracts\Filesystem\Factory filesystem
URL Illuminate\Routing\UrlGenerator url
Validator Illuminate\Validation\Factory validator
Validator (Instancia) Illuminate\Validation\Validator
View Illuminate\View\Factory view
View (Instancia) Illuminate\View\View