Laravel 中使用的 Facade 是什么?

What is Facades used in Laravel?

我对 Laravel 提供的门面感到困惑。

Laravel documentation 状态:

Facades provide a "static" interface to classes that are available in the application's service container. Laravel ships with many facades which provide access to almost all of Laravel's features. Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

请帮助我理解:

  1. 为什么我们真的使用 use Illuminate\Support\Facades
  2. 如何创建自定义外观?

支持 SitePoint 在 Laravel 中分享关于立面的信息和有用的知识。

门面模式是一种软件设计模式,在object-oriented编程中经常使用。

外观 是class 包装一个复杂的库以提供一个更简单和更易读的接口。

立面 Laravel

Facades 为应用程序服务容器中可用的 classes 提供了一个“静态”接口。 Laravel 附带许多外观,可以访问几乎所有 Laravel 的功能。 Laravel facades 充当服务容器中底层 classes 的“静态代理”,提供简洁、富有表现力的语法,同时保持比传统静态方法更多的可测试性和灵活性。

如何在 Laravel

中实现门面

容器内的每个服务都有一个唯一的名称。在 Laravel 应用程序中,要直接从容器访问服务,我们可以使用 App::make() 方法或 app() 辅助函数。

<?php

App::make('some_service')->methodName();

在Laravel中,所有服务都有一个门面class。这些门面 class 扩展了基础门面 class,它是 Illuminate/Support 包的一部分。他们唯一需要实现的是 getFacadeAccessor 方法,该方法 returns 容器内的服务名称。

看这个例子就明白了

DB::table('table_name')->get();  

在此示例中,DB 是门面。它正在 DB facade.

上调用 table() 静态方法

一般来说,立面(发音为 /fəˈsɑːd/)是建筑物或任何事物的外部和正面。立面的重要性在于它们很容易被注意到并且更突出,同样在 laravel 中也有立面的概念。它们用于管理我们的代码可读性并构建易于记忆的函数语法和 classes。

Laravel 外观是一个 class,它为服务容器内的服务提供类静态接口。它们充当访问 laravel 服务的底层实现的代理。例如在 web.php 文件

中写入以下代码
//using redis cache
Route::get('/cache', function () {
    cache()->put('hello','world', 600);
    dd(cache()->get('hello')); //outputs world
});

上面的例子是使用非静态方式调用缓存的方法,现在让我们看看我们如何使用缓存外观。

use Illuminate\Support\Facades\Cache;
//using redis cache
Route::get('/cache', function () {
    Cache::put('hello','world', 600);
    dd(Cache::get('hello'));
});

你不觉得上面的例子更优雅,语法更容易记住,对吧?这就是立面之美。