Skip to content

门面

介绍

在 Laravel 文档中,您会看到许多通过“门面”与 Laravel 功能交互的代码示例。门面为应用程序的服务容器中可用的类提供了一个“静态”接口。Laravel 附带了许多门面,提供对几乎所有 Laravel 功能的访问。

Laravel 门面充当服务容器中底层类的“静态代理”,提供简洁、富有表现力的语法,同时比传统的静态方法具有更高的可测试性和灵活性。如果您不完全理解门面的工作原理也没关系——只需顺其自然,继续学习 Laravel。

所有 Laravel 的门面都定义在 Illuminate\Support\Facades 命名空间中。因此,我们可以轻松地访问一个门面,如下所示:

php
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

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

在整个 Laravel 文档中,许多示例将使用门面来演示框架的各种功能。

辅助函数

为了补充门面,Laravel 提供了多种全局“辅助函数”,使与常见 Laravel 功能的交互更加容易。您可能会使用的一些常见辅助函数包括 viewresponseurlconfig 等。Laravel 提供的每个辅助函数都在其对应的功能中进行了记录;然而,完整列表可在专用的辅助文档中找到。

例如,我们可以使用 response 函数生成 JSON 响应,而不是使用 Illuminate\Support\Facades\Response 门面。由于辅助函数是全局可用的,您无需导入任何类即可使用它们:

php
use Illuminate\Support\Facades\Response;

Route::get('/users', function () {
    return Response::json([
        // ...
    ]);
});

Route::get('/users', function () {
    return response()->json([
        // ...
    ]);
});

何时使用门面

门面有许多优点。它们提供了简洁、易记的语法,使您无需记住长类名即可使用 Laravel 的功能,这些类名必须手动注入或配置。此外,由于它们独特地使用 PHP 的动态方法,它们易于测试。

然而,使用门面时必须小心。门面的主要危险是类的“范围蔓延”。由于门面使用起来非常简单且不需要注入,因此很容易让您的类继续增长,并在单个类中使用许多门面。使用依赖注入,这种潜力通过大型构造函数提供的视觉反馈得以缓解,提醒您类的增长过大。因此,使用门面时,请特别注意类的大小,以确保其责任范围保持狭窄。如果您的类变得过大,请考虑将其拆分为多个较小的类。

门面 vs. 依赖注入

依赖注入的主要优点之一是能够交换注入类的实现。这在测试期间非常有用,因为您可以注入一个模拟或存根,并断言在存根上调用了各种方法。

通常,不可能模拟或存根真正的静态类方法。然而,由于门面使用动态方法将方法调用代理到从服务容器解析的对象,我们实际上可以像测试注入的类实例一样测试门面。例如,给定以下路由:

php
use Illuminate\Support\Facades\Cache;

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

使用 Laravel 的门面测试方法,我们可以编写以下测试来验证 Cache::get 方法是否使用我们期望的参数调用:

php
use Illuminate\Support\Facades\Cache;

/**
 * 一个基本的功能测试示例。
 */
public function test_basic_example(): void
{
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

    $response = $this->get('/cache');

    $response->assertSee('value');
}

门面 vs. 辅助函数

除了门面,Laravel 还包括多种“辅助”函数,可以执行常见任务,如生成视图、触发事件、调度作业或发送 HTTP 响应。许多这些辅助函数执行与相应门面相同的功能。例如,这个门面调用和辅助调用是等效的:

php
return Illuminate\Support\Facades\View::make('profile');

return view('profile');

门面和辅助函数之间没有实际区别。使用辅助函数时,您仍然可以像测试相应门面一样测试它们。例如,给定以下路由:

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

cache 辅助函数将调用 Cache 门面底层类的 get 方法。因此,即使我们使用辅助函数,我们也可以编写以下测试来验证方法是否使用我们期望的参数调用:

php
use Illuminate\Support\Facades\Cache;

/**
 * 一个基本的功能测试示例。
 */
public function test_basic_example(): void
{
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

    $response = $this->get('/cache');

    $response->assertSee('value');
}

门面的工作原理

在 Laravel 应用程序中,门面是一个类,用于从容器中访问对象。使这项工作成为可能的机制在 Facade 类中。Laravel 的门面以及您创建的任何自定义门面都将扩展基础 Illuminate\Support\Facades\Facade 类。

Facade 基类利用 __callStatic() 魔术方法将您的门面调用推迟到从容器解析的对象。在下面的示例中,调用了 Laravel 缓存系统。通过查看此代码,人们可能会认为静态 get 方法正在 Cache 类上调用:

php
<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * 显示给定用户的个人资料。
     */
    public function showProfile(string $id): View
    {
        $user = Cache::get('user:'.$id);

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

请注意,在文件顶部附近,我们正在“导入” Cache 门面。此门面充当访问 Illuminate\Contracts\Cache\Factory 接口底层实现的代理。我们使用门面进行的任何调用都将传递给 Laravel 缓存服务的底层实例。

如果我们查看 Illuminate\Support\Facades\Cache 类,您会看到没有静态方法 get

php
class Cache extends Facade
{
    /**
     * 获取组件的注册名称。
     */
    protected static function getFacadeAccessor(): string
    {
        return 'cache';
    }
}

相反,Cache 门面扩展了基础 Facade 类,并定义了 getFacadeAccessor() 方法。此方法的工作是返回服务容器绑定的名称。当用户在 Cache 门面上引用任何静态方法时,Laravel 从服务容器解析 cache 绑定,并在该对象上运行请求的方法(在本例中为 get)。

实时门面

使用实时门面,您可以将应用程序中的任何类视为门面。为了说明如何使用它,让我们首先检查一些不使用实时门面的代码。例如,假设我们的 Podcast 模型有一个 publish 方法。然而,为了发布播客,我们需要注入一个 Publisher 实例:

php
<?php

namespace App\Models;

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

class Podcast extends Model
{
    /**
     * 发布播客。
     */
    public function publish(Publisher $publisher): void
    {
        $this->update(['publishing' => now()]);

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

将发布者实现注入方法中,使我们能够轻松地在隔离中测试该方法,因为我们可以模拟注入的发布者。然而,这要求我们每次调用 publish 方法时都显式传递一个发布者实例。使用实时门面,我们可以保持相同的可测试性,而无需显式传递 Publisher 实例。要生成实时门面,请在导入类的命名空间前加上 Facades 前缀:

php
<?php

namespace App\Models;

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

class Podcast extends Model
{
    /**
     * 发布播客。
     */
    public function publish(Publisher $publisher): void
    public function publish(): void
    {
        $this->update(['publishing' => now()]);

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

使用实时门面时,将使用接口或类名中 Facades 前缀后面的部分从服务容器中解析发布者实现。在测试时,我们可以使用 Laravel 内置的门面测试助手来模拟此方法调用:

php
<?php

namespace Tests\Feature;

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

class PodcastTest extends TestCase
{
    use RefreshDatabase;

    /**
     * 一个测试示例。
     */
    public function test_podcast_can_be_published(): void
    {
        $podcast = Podcast::factory()->create();

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

        $podcast->publish();
    }
}

门面类参考

下面您将找到每个门面及其底层类。这是快速深入了解给定门面根的 API 文档的有用工具。还包括服务容器绑定键(如果适用)。

门面服务容器绑定
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
DateIlluminate\Support\DateFactorydate
DBIlluminate\Database\DatabaseManagerdb
DB (Instance)Illuminate\Database\Connectiondb.connection
EventIlluminate\Events\Dispatcherevents
FileIlluminate\Filesystem\Filesystemfiles
GateIlluminate\Contracts\Auth\Access\Gate 
HashIlluminate\Contracts\Hashing\Hasherhash
HttpIlluminate\Http\Client\Factory 
LangIlluminate\Translation\Translatortranslator
LogIlluminate\Log\LogManagerlog
MailIlluminate\Mail\Mailermailer
NotificationIlluminate\Notifications\ChannelManager 
PasswordIlluminate\Auth\Passwords\PasswordBrokerManagerauth.password
Password (Instance)Illuminate\Auth\Passwords\PasswordBrokerauth.password.broker
Pipeline (Instance)Illuminate\Pipeline\Pipeline 
ProcessIlluminate\Process\Factory 
QueueIlluminate\Queue\QueueManagerqueue
Queue (Instance)Illuminate\Contracts\Queue\Queuequeue.connection
Queue (Base Class)Illuminate\Queue\Queue 
RateLimiterIlluminate\Cache\RateLimiter 
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 
ViteIlluminate\Foundation\Vite