Skip to content

Facades

介绍

在 Laravel 文档中,你会看到许多通过 "facades" 与 Laravel 功能交互的代码示例。Facades 提供了一个 "静态" 接口来访问应用程序的 服务容器 中的类。Laravel 附带了许多 facades,几乎可以访问 Laravel 的所有功能。

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

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

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

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

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

辅助函数

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

例如,代替使用 Illuminate\Support\Facades\Response facade 来生成 JSON 响应,我们可以简单地使用 response 函数。因为辅助函数是全局可用的,所以你不需要导入任何类来使用它们:

use Illuminate\Support\Facades\Response;

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

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

何时使用 Facades

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

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

Facades vs. 依赖注入

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

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

use Illuminate\Support\Facades\Cache;

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

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

use Illuminate\Support\Facades\Cache;

test('basic example', function () {
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

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

    $response->assertSee('value');
});
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');
}

Facades vs. 辅助函数

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

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

return view('profile');

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

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

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

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

Facades 的工作原理

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

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

<?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 facade。这个 facade 作为访问 Illuminate\Contracts\Cache\Factory 接口底层实现的代理。我们使用 facade 进行的任何调用都将传递给 Laravel 缓存服务的底层实例。

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

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

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

实时 Facades

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

<?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 方法时都显式传递一个发布者实例。使用实时 facades,我们可以保持相同的可测试性,而不需要显式传递 Publisher 实例。要生成实时 facade,请在导入类的命名空间前加上 Facades 前缀:

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

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

<?php

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

uses(RefreshDatabase::class);

test('podcast can be published', function () {
    $podcast = Podcast::factory()->create();

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

    $podcast->publish();
});
<?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();
    }
}

Facade 类参考

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

Facade服务容器绑定
App[Illuminate\Foundation\Application](https://laravel.com/api/11.x/Illuminate/Foundation/Application.html)`app`
Artisan[Illuminate\Contracts\Console\Kernel](https://laravel.com/api/11.x/Illuminate/Contracts/Console/Kernel.html)`artisan`
Auth (实例)[Illuminate\Contracts\Auth\Guard](https://laravel.com/api/11.x/Illuminate/Contracts/Auth/Guard.html)`auth.driver`
Auth[Illuminate\Auth\AuthManager](https://laravel.com/api/11.x/Illuminate/Auth/AuthManager.html)`auth`
Blade[Illuminate\View\Compilers\BladeCompiler](https://laravel.com/api/11.x/Illuminate/View/Compilers/BladeCompiler.html)`blade.compiler`
Broadcast (实例)[Illuminate\Contracts\Broadcasting\Broadcaster](https://laravel.com/api/11.x/Illuminate/Contracts/Broadcasting/Broadcaster.html) 
Broadcast[Illuminate\Contracts\Broadcasting\Factory](https://laravel.com/api/11.x/Illuminate/Contracts/Broadcasting/Factory.html) 
Bus[Illuminate\Contracts\Bus\Dispatcher](https://laravel.com/api/11.x/Illuminate/Contracts/Bus/Dispatcher.html) 
Cache (实例)[Illuminate\Cache\Repository](https://laravel.com/api/11.x/Illuminate/Cache/Repository.html)`cache.store`
Cache[Illuminate\Cache\CacheManager](https://laravel.com/api/11.x/Illuminate/Cache/CacheManager.html)`cache`
Config[Illuminate\Config\Repository](https://laravel.com/api/11.x/Illuminate/Config/Repository.html)`config`
Context[Illuminate\Log\Context\Repository](https://laravel.com/api/11.x/Illuminate/Log/Context/Repository.html) 
Cookie[Illuminate\Cookie\CookieJar](https://laravel.com/api/11.x/Illuminate/Cookie/CookieJar.html)`cookie`
Crypt[Illuminate\Encryption\Encrypter](https://laravel.com/api/11.x/Illuminate/Encryption/Encrypter.html)`encrypter`
Date[Illuminate\Support\DateFactory](https://laravel.com/api/11.x/Illuminate/Support/DateFactory.html)`date`
DB (实例)[Illuminate\Database\Connection](https://laravel.com/api/11.x/Illuminate/Database/Connection.html)`db.connection`
DB[Illuminate\Database\DatabaseManager](https://laravel.com/api/11.x/Illuminate/Database/DatabaseManager.html)`db`
Event[Illuminate\Events\Dispatcher](https://laravel.com/api/11.x/Illuminate/Events/Dispatcher.html)`events`
Exceptions (实例)[Illuminate\Contracts\Debug\ExceptionHandler](https://laravel.com/api/11.x/Illuminate/Contracts/Debug/ExceptionHandler.html) 
Exceptions[Illuminate\Foundation\Exceptions\Handler](https://laravel.com/api/11.x/Illuminate/Foundation/Exceptions/Handler.html) 
File[Illuminate\Filesystem\Filesystem](https://laravel.com/api/11.x/Illuminate/Filesystem/Filesystem.html)`files`
Gate[Illuminate\Contracts\Auth\Access\Gate](https://laravel.com/api/11.x/Illuminate/Contracts/Auth/Access/Gate.html) 
Hash[Illuminate\Contracts\Hashing\Hasher](https://laravel.com/api/11.x/Illuminate/Contracts/Hashing/Hasher.html)`hash`
Http[Illuminate\Http\Client\Factory](https://laravel.com/api/11.x/Illuminate/Http/Client/Factory.html) 
Lang[Illuminate\Translation\Translator](https://laravel.com/api/11.x/Illuminate/Translation/Translator.html)`translator`
Log[Illuminate\Log\LogManager](https://laravel.com/api/11.x/Illuminate/Log/LogManager.html)`log`
Mail[Illuminate\Mail\Mailer](https://laravel.com/api/11.x/Illuminate/Mail/Mailer.html)`mailer`
Notification[Illuminate\Notifications\ChannelManager](https://laravel.com/api/11.x/Illuminate/Notifications/ChannelManager.html) 
Password (实例)[Illuminate\Auth\Passwords\PasswordBroker](https://laravel.com/api/11.x/Illuminate/Auth/Passwords/PasswordBroker.html)`auth.password.broker`
Password[Illuminate\Auth\Passwords\PasswordBrokerManager](https://laravel.com/api/11.x/Illuminate/Auth/Passwords/PasswordBrokerManager.html)`auth.password`
Pipeline (实例)[Illuminate\Pipeline\Pipeline](https://laravel.com/api/11.x/Illuminate/Pipeline/Pipeline.html) 
Process[Illuminate\Process\Factory](https://laravel.com/api/11.x/Illuminate/Process/Factory.html) 
Queue (基类)[Illuminate\Queue\Queue](https://laravel.com/api/11.x/Illuminate/Queue/Queue.html) 
Queue (实例)[Illuminate\Contracts\Queue\Queue](https://laravel.com/api/11.x/Illuminate/Contracts/Queue/Queue.html)`queue.connection`
Queue[Illuminate\Queue\QueueManager](https://laravel.com/api/11.x/Illuminate/Queue/QueueManager.html)`queue`
RateLimiter[Illuminate\Cache\RateLimiter](https://laravel.com/api/11.x/Illuminate/Cache/RateLimiter.html) 
Redirect[Illuminate\Routing\Redirector](https://laravel.com/api/11.x/Illuminate/Routing/Redirector.html)`redirect`
Redis (实例)[Illuminate\Redis\Connections\Connection](https://laravel.com/api/11.x/Illuminate/Redis/Connections/Connection.html)`redis.connection`
Redis[Illuminate\Redis\RedisManager](https://laravel.com/api/11.x/Illuminate/Redis/RedisManager.html)`redis`
Request[Illuminate\Http\Request](https://laravel.com/api/11.x/Illuminate/Http/Request.html)`request`
Response (实例)[Illuminate\Http\Response](https://laravel.com/api/11.x/Illuminate/Http/Response.html) 
Response[Illuminate\Contracts\Routing\ResponseFactory](https://laravel.com/api/11.x/Illuminate/Contracts/Routing/ResponseFactory.html) 
Route[Illuminate\Routing\Router](https://laravel.com/api/11.x/Illuminate/Routing/Router.html)`router`
Schedule[Illuminate\Console\Scheduling\Schedule](https://laravel.com/api/11.x/Illuminate/Console/Scheduling/Schedule.html) 
Schema[Illuminate\Database\Schema\Builder](https://laravel.com/api/11.x/Illuminate/Database/Schema/Builder.html) 
Session (实例)[Illuminate\Session\Store](https://laravel.com/api/11.x/Illuminate/Session/Store.html)`session.store`
Session[Illuminate\Session\SessionManager](https://laravel.com/api/11.x/Illuminate/Session/SessionManager.html)`session`
Storage (实例)[Illuminate\Contracts\Filesystem\Filesystem](https://laravel.com/api/11.x/Illuminate/Contracts/Filesystem/Filesystem.html)`filesystem.disk`
Storage[Illuminate\Filesystem\FilesystemManager](https://laravel.com/api/11.x/Illuminate/Filesystem/FilesystemManager.html)`filesystem`
URL[Illuminate\Routing\UrlGenerator](https://laravel.com/api/11.x/Illuminate/Routing/UrlGenerator.html)`url`
Validator (实例)[Illuminate\Validation\Validator](https://laravel.com/api/11.x/Illuminate/Validation/Validator.html) 
Validator[Illuminate\Validation\Factory](https://laravel.com/api/11.x/Illuminate/Validation/Factory.html)`validator`
View (实例)[Illuminate\View\View](https://laravel.com/api/11.x/Illuminate/View/View.html) 
View[Illuminate\View\Factory](https://laravel.com/api/11.x/Illuminate/View/Factory.html)`view`
Vite[Illuminate\Foundation\Vite](https://laravel.com/api/11.x/Illuminate/Foundation/Vite.html)