Laravel Facades

Facades提供了一個「靜態」的接口到應用程序的服務容器中可用的類。 Laravel 的「facades」作爲「靜態代理」在服務容器底層類,提供了一個簡潔, 富有表現的語法,同時保持比傳統的靜態方法更有可測試性和靈活性。

如何創建Facade


以下是在Laravel創建 Facade 的步驟:

  • 第1步 - 創建PHP類文件

  • 第2步 - 綁定類到服務提供者

  • 第3步- 註冊服務提供者到 Config\app.php 作爲供應者

  • 第4步- 創建類,這個類是擴展lluminate\Support\Facades\Facade

  • 第5步- 註冊第4點到 Config\app.php 作爲別名

Facade類參考


Laravel附帶許多Facades。下面是內置的Facades類引用。

Facade

服務容器綁定

App

Illuminate\Foundation\Application

app

Artisan

Illuminate\Contracts\Console\Kernel

artisan

Auth

Illuminate\Auth\AuthManager

auth

Auth (Instance)

Illuminate\Auth\Guard

Blade

Illuminate\View\Compilers\BladeCompiler

blade.compiler

Bus

Illuminate\Contracts\Bus\Dispatcher

Cache

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 (Instance)

Illuminate\Database\Connection

Event

Illuminate\Events\Dispatcher

events

File

Illuminate\Filesystem\Filesystem

files

Gate

Illuminate\Contracts\Auth\Access\Gate

Hash

Illuminate\Contracts\Hashing\Hasher

hash

Input

Illuminate\Http\Request

request

Lang

Illuminate\Translation\Translator

translator

Log

Illuminate\Log\Writer

log

Mail

Illuminate\Mail\Mailer

mailer

Password

Illuminate\Auth\Passwords\PasswordBroker

auth.password

Queue

Illuminate\Queue\QueueManager

queue

Queue (Instance)

Illuminate\Queue\QueueInterface

Queue (Base Class)

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

Session

Illuminate\Session\SessionManager

session

Session (Instance)

Illuminate\Session\Store

Storage

Illuminate\Contracts\Filesystem\Factory

filesystem

URL

Illuminate\Routing\UrlGenerator

url

Validator

Illuminate\Validation\Factory

validator

Validator (Instance)

Illuminate\Validation\Validator

View

Illuminate\View\Factory

view

View (Instance)

Illuminate\View\View

示例

第1步- 執行以下命令創建一個叫作 TestFacadesServiceProvider 的服務提供者。

php artisan make:provider TestFacadesServiceProvider

第2步 - 成功執行後,您會收到以下輸出 -
Laravel

第3步 - 在「App/Test」創建一個名爲 「TestFacades.php」的類

App/Test/TestFacades.php

App\\Test\\Facades\\TestFacades::class,  第8步 - 添加以下行到文件 - app/Http/routes.php app/Http/routes.php Route::get('/facadeex', function(){ return TestFacades::testingFacades(); }); 第9步 - 訪問以下網址測試 Facade https://asset.1ju.org/facadeex 第10步 - 訪問URL後,您會收到以下輸出 - ![Laravel Facades](https://asset.1ju.org/cmsstatic/laravel-facades-2.png)