Laravel Docs RU
  • Laravel 7
  • Начало работы
    • Установка
    • Конфигурация
    • Структура директорий
    • Homestead
    • Valet
    • Развертывание
  • Архитектура
    • Жизненный цикл запроса
    • Service Container
    • Service Providers
    • Фасады
    • Контракты
  • Основы
    • Маршрутизация
    • Посредники (Middleware)
    • CSRF защита
    • Контроллеры
    • URL Generation
    • Сессии
    • Валидация
  • Фронтэнд
    • Blade шаблоны
    • Локализация
  • Безопасность
    • Аутентификация
    • Авторизация
  • Копаем глубже
    • Консоль Artisan
    • Broadcasting
    • Кэширование
    • Коллекции
    • События
    • Файловое хранилище
    • Помощники
    • HTTP клиент
    • Электронная почта
    • Уведомления
    • Разработка пакетов
    • Очереди
    • Планировщик задач
  • База банных
    • Начало работы
    • Конструктор запросов
  • Eloquent ORM
    • Начало работы
  • Официальные пакеты
    • Laravel Passport
Powered by GitBook
On this page
  • Вступление
  • Когда использовать фасады
  • Фасады Против Внедрения зависимостей
  • Facades Vs. Helper Functions
  • How Facades Work
  • Real-Time Facades
  • Facade Class Reference

Was this helpful?

  1. Архитектура

Фасады

PreviousService ProvidersNextКонтракты

Last updated 4 years ago

Was this helpful?

Вступление

Фасады обеспечивают "статический" интерфейс к классам, которые доступны в приложения. Laravel имеет множество фасадов, которые обеспечивают доступ почти ко всем возможностям фреймворка. Фасады служат "статическими прокси" к базовым классам в сервисном контейнере, обеспечивая преимущество лаконичного, экспрессивного синтаксиса при сохранении большей тестируемости и гибкости по сравнению с традиционными статическими методами.

Все фасады Laravel определены в пространстве имен Illuminate\Support\Facades. Таким образом, мы можем легко получить доступ к такому фасаду:

use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
    return Cache::get('key');
});

Во всей документации Laravel многие примеры будут использовать фасады для демонстрации различных особенностей фреймворка.

Когда использовать фасады

Фасады имеют много преимуществ. Они обеспечивают лаконичный, запоминающийся синтаксис, который позволяет использовать функции Laravel, не запоминая длинные названия классов, которые необходимо вводить или настраивать вручную. Более того, благодаря уникальному использованию динамических методов PHP, они легко тестируются.

Тем не менее, при использовании фасадов необходимо проявлять некоторую осторожность. Основная опасность фасадов — это ползучесть по классу. Так как фасады настолько просты в использовании и не требуют внедрения, можно легко позволить Вашим классам продолжать расти и использовать много фасадов в одном классе. Используя внедрение зависимостей, этот потенциал смягчается визуальной обратной связью, которую дает вам большой конструктор, что ваш класс растет слишком большим. Поэтому, при использовании фасадов, обратите особое внимание на размер вашего класса, чтобы сфера его ответственности оставалась узкой.

При создании стороннего пакета, взаимодействующего с Laravel, лучше сделать внедрение вместо использования фасадов. Поскольку пакеты создаются вне самой Laravel, у вас не будет доступа к помощникам Laravel по тестированию фасадов.

Фасады Против Внедрения зависимостей

Одним из основных преимуществ внедрения зависимостей является возможность обмена реализациями внедряемого класса. Это полезно при тестировании, так как можно вводить имитацию или заглушку и утверждать, что различные методы были вызваны в заглушке.

Обычно невозможно имитировать или заглушить по-настоящему статический метод класса. Однако, поскольку фасады используют динамические методы для прокси вызова методов к объектам, разрешенным из сервисного контейнера, мы фактически можем тестировать фасады точно так же, как мы тестировали бы внедряемый экземпляр класса. Например, учитывая следующий маршрут:

use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
    return Cache::get('key');
});

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

use Illuminate\Support\Facades\Cache;

/**
 * A basic functional test example.
 *
 * @return void
 */
public function testBasicExample()
{
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

    $this->visit('/cache')
         ->see('value');
}

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:

return View::make('profile');

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:

Route::get('/cache', function () {
    return cache('key');
});

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:

use Illuminate\Support\Facades\Cache;

/**
 * A basic functional test example.
 *
 * @return void
 */
public function testBasicExample()
{
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

    $this->visit('/cache')
         ->see('value');
}

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:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

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'; }
}

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:

<?php

namespace App;

use App\Contracts\Publisher;
use Illuminate\Database\Eloquent\Model;

class Podcast extends Model
{
    /**
     * Publish the podcast.
     *
     * @param  Publisher  $publisher
     * @return void
     */
    public function publish(Publisher $publisher)
    {
        $this->update(['publishing' => now()]);

        $publisher->publish($this);
    }
}

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:

<?php

namespace App;

use Facades\App\Contracts\Publisher;
use Illuminate\Database\Eloquent\Model;

class Podcast extends Model
{
    /**
     * Publish the podcast.
     *
     * @return void
     */
    public function publish()
    {
        $this->update(['publishing' => now()]);

        Publisher::publish($this);
    }
}

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:

<?php

namespace Tests\Feature;

use App\Podcast;
use Facades\App\Contracts\Publisher;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PodcastTest extends TestCase
{
    use RefreshDatabase;

    /**
     * A test example.
     *
     * @return void
     */
    public function test_podcast_can_be_published()
    {
        $podcast = factory(Podcast::class)->create();

        Publisher::shouldReceive('publish')->once()->with($podcast);

        $podcast->publish();
    }
}

Facade Class Reference

Facade

Class

Service Container Binding

App

app

Artisan

artisan

Auth

auth

Auth (Instance)

auth.driver

Blade

blade.compiler

Broadcast

Broadcast (Instance)

Bus

Cache

cache

Cache (Instance)

cache.store

Config

config

Cookie

cookie

Crypt

encrypter

DB

db

DB (Instance)

db.connection

Event

events

File

files

Gate

Hash

hash

Http

Lang

translator

Log

log

Mail

mailer

Notification

Password

auth.password

Password (Instance)

auth.password.broker

Queue

queue

Queue (Instance)

queue.connection

Queue (Base Class)

Redirect

redirect

Redis

redis

Redis (Instance)

redis.connection

Request

request

Response

Response (Instance)

Route

router

Schema

Session

session

Session (Instance)

session.store

Storage

filesystem

Storage (Instance)

filesystem.disk

URL

url

Validator

validator

Validator (Instance)

View

view

View (Instance)

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.

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 key is also included where applicable.

service container
service container binding
Illuminate\Foundation\Application
Illuminate\Contracts\Console\Kernel
Illuminate\Auth\AuthManager
Illuminate\Contracts\Auth\Guard
Illuminate\View\Compilers\BladeCompiler
Illuminate\Contracts\Broadcasting\Factory
Illuminate\Contracts\Broadcasting\Broadcaster
Illuminate\Contracts\Bus\Dispatcher
Illuminate\Cache\CacheManager
Illuminate\Cache\Repository
Illuminate\Config\Repository
Illuminate\Cookie\CookieJar
Illuminate\Encryption\Encrypter
Illuminate\Database\DatabaseManager
Illuminate\Database\Connection
Illuminate\Events\Dispatcher
Illuminate\Filesystem\Filesystem
Illuminate\Contracts\Auth\Access\Gate
Illuminate\Contracts\Hashing\Hasher
Illuminate\Http\Client\Factory
Illuminate\Translation\Translator
Illuminate\Log\LogManager
Illuminate\Mail\Mailer
Illuminate\Notifications\ChannelManager
Illuminate\Auth\Passwords\PasswordBrokerManager
Illuminate\Auth\Passwords\PasswordBroker
Illuminate\Queue\QueueManager
Illuminate\Contracts\Queue\Queue
Illuminate\Queue\Queue
Illuminate\Routing\Redirector
Illuminate\Redis\RedisManager
Illuminate\Redis\Connections\Connection
Illuminate\Http\Request
Illuminate\Contracts\Routing\ResponseFactory
Illuminate\Http\Response
Illuminate\Routing\Router
Illuminate\Database\Schema\Builder
Illuminate\Session\SessionManager
Illuminate\Session\Store
Illuminate\Filesystem\FilesystemManager
Illuminate\Contracts\Filesystem\Filesystem
Illuminate\Routing\UrlGenerator
Illuminate\Validation\Factory
Illuminate\Validation\Validator
Illuminate\View\Factory
Illuminate\View\View
service container
Laravel Contracts