Laravel之Contracts和Facades詳解

来源:https://www.cnblogs.com/a609251438/archive/2020/04/15/12707971.html
-Advertisement-
Play Games

Contracts Contracts其實就是倡導面向介面編程,來達到解耦的目的。而這些通用的介面已經由Laravel為你設計好了。就是這些Contracts. 那麼Laravel如何知道我們需要使用哪個實現呢? 在Laravel預設的Contracts綁定中,在'Illuminate/Founda ...


Contracts

 

Contracts其實就是倡導面向介面編程,來達到解耦的目的。而這些通用的介面已經由Laravel為你設計好了。就是這些Contracts.

那麼Laravel如何知道我們需要使用哪個實現呢?

在Laravel預設的Contracts綁定中,在'Illuminate/Foundation/Application.php'有這樣的定義:這就是綁定了預設的介面實現.

/**

     * Register the core class aliases in the container.

     *

     * @return void

     */

    public function registerCoreContainerAliases()

    {

        $aliases = [

            'app'                  => ['Illuminate\Foundation\Application', 'Illuminate\Contracts\Container\Container', 'Illuminate\Contracts\Foundation\Application'],

            'auth'                 => 'Illuminate\Auth\AuthManager',

            'auth.driver'          => ['Illuminate\Auth\Guard', 'Illuminate\Contracts\Auth\Guard'],

            'auth.password.tokens' => 'Illuminate\Auth\Passwords\TokenRepositoryInterface',

            'blade.compiler'       => 'Illuminate\View\Compilers\BladeCompiler',

            'cache'                => ['Illuminate\Cache\CacheManager', 'Illuminate\Contracts\Cache\Factory'],

            'cache.store'          => ['Illuminate\Cache\Repository', 'Illuminate\Contracts\Cache\Repository'],

            'config'               => ['Illuminate\Config\Repository', 'Illuminate\Contracts\Config\Repository'],

            'cookie'               => ['Illuminate\Cookie\CookieJar', 'Illuminate\Contracts\Cookie\Factory', 'Illuminate\Contracts\Cookie\QueueingFactory'],

            'encrypter'            => ['Illuminate\Encryption\Encrypter', 'Illuminate\Contracts\Encryption\Encrypter'],

            'db'                   => 'Illuminate\Database\DatabaseManager',

            'db.connection'        => ['Illuminate\Database\Connection', 'Illuminate\Database\ConnectionInterface'],

            'events'               => ['Illuminate\Events\Dispatcher', 'Illuminate\Contracts\Events\Dispatcher'],

            'files'                => 'Illuminate\Filesystem\Filesystem',

            'filesystem'           => ['Illuminate\Filesystem\FilesystemManager', 'Illuminate\Contracts\Filesystem\Factory'],

            'filesystem.disk'      => 'Illuminate\Contracts\Filesystem\Filesystem',

            'filesystem.cloud'     => 'Illuminate\Contracts\Filesystem\Cloud',

            'hash'                 => 'Illuminate\Contracts\Hashing\Hasher',

            'translator'           => ['Illuminate\Translation\Translator', 'Symfony\Component\Translation\TranslatorInterface'],

            'log'                  => ['Illuminate\Log\Writer', 'Illuminate\Contracts\Logging\Log', 'Psr\Log\LoggerInterface'],

            'mailer'               => ['Illuminate\Mail\Mailer', 'Illuminate\Contracts\Mail\Mailer', 'Illuminate\Contracts\Mail\MailQueue'],

            'auth.password'        => ['Illuminate\Auth\Passwords\PasswordBroker', 'Illuminate\Contracts\Auth\PasswordBroker'],

            'queue'                => ['Illuminate\Queue\QueueManager', 'Illuminate\Contracts\Queue\Factory', 'Illuminate\Contracts\Queue\Monitor'],

            'queue.connection'     => 'Illuminate\Contracts\Queue\Queue',

            'redirect'             => 'Illuminate\Routing\Redirector',

            'redis'                => ['Illuminate\Redis\Database', 'Illuminate\Contracts\Redis\Database'],

            'request'              => 'Illuminate\Http\Request',

            'router'               => ['Illuminate\Routing\Router', 'Illuminate\Contracts\Routing\Registrar'],

            'session'              => 'Illuminate\Session\SessionManager',

            'session.store'        => ['Illuminate\Session\Store', 'Symfony\Component\HttpFoundation\Session\SessionInterface'],

            'url'                  => ['Illuminate\Routing\UrlGenerator', 'Illuminate\Contracts\Routing\UrlGenerator'],

            'validator'            => ['Illuminate\Validation\Factory', 'Illuminate\Contracts\Validation\Factory'],

            'view'                 => ['Illuminate\View\Factory', 'Illuminate\Contracts\View\Factory'],

        ];

  

在我們自定義的介面實現時,我們可以在ServiceProvider中使用進行綁定:

$this->app->bind('App\Contracts\EventPusher', 'App\Services\PusherEventPusher');

  

Facades

Facades 為應用程式的服務容器中可用的類提供了一個「靜態」介面。Laravel 「facades」作為在服務容器內基類的「靜態代理」。很難懂?

我們打開項目目錄下的config/app.php,然後找到

/*

    |--------------------------------------------------------------------------

    | Class Aliases

    |--------------------------------------------------------------------------

    |

    | This array of class aliases will be registered when this application

    | is started. However, feel free to register as many as you wish as

    | the aliases are "lazy" loaded so they don't hinder performance.

    |

    */

    'aliases' => [

        'App'       => Illuminate\Support\Facades\App::class,

        'Artisan'   => Illuminate\Support\Facades\Artisan::class,

        'Auth'      => Illuminate\Support\Facades\Auth::class,

        'Blade'     => Illuminate\Support\Facades\Blade::class,

        'Bus'       => Illuminate\Support\Facades\Bus::class,

        'Cache'     => Illuminate\Support\Facades\Cache::class,

        'Config'    => Illuminate\Support\Facades\Config::class,

        'Cookie'    => Illuminate\Support\Facades\Cookie::class,

        'Crypt'     => Illuminate\Support\Facades\Crypt::class,

        'DB'        => Illuminate\Support\Facades\DB::class,

        'Eloquent'  => Illuminate\Database\Eloquent\Model::class,

        'Event'     => Illuminate\Support\Facades\Event::class,

        'File'      => Illuminate\Support\Facades\File::class,

        'Gate'      => Illuminate\Support\Facades\Gate::class,

        'Hash'      => Illuminate\Support\Facades\Hash::class,

        'Input'     => Illuminate\Support\Facades\Input::class,

        'Lang'      => Illuminate\Support\Facades\Lang::class,

        'Log'       => Illuminate\Support\Facades\Log::class,

        'Mail'      => Illuminate\Support\Facades\Mail::class,

        'Password'  => Illuminate\Support\Facades\Password::class,

        'Queue'     => Illuminate\Support\Facades\Queue::class,

        'Redirect'  => Illuminate\Support\Facades\Redirect::class,

        'Redis'     => Illuminate\Support\Facades\Redis::class,

        'Request'   => Illuminate\Support\Facades\Request::class,

        'Response'  => Illuminate\Support\Facades\Response::class,

        'Route'     => Illuminate\Support\Facades\Route::class,

        'Schema'    => Illuminate\Support\Facades\Schema::class,

        'Session'   => Illuminate\Support\Facades\Session::class,

        'Storage'   => Illuminate\Support\Facades\Storage::class,

        'URL'       => Illuminate\Support\Facades\URL::class,

        'Validator' => Illuminate\Support\Facades\Validator::class,

        'View'      => Illuminate\Support\Facades\View::class,

    ],

  

你是不是發現了什麼?對,Facades其實就是在config/app.php中定義的一系列類的別名。只不過這些類都具有一個共同的特點,那就是繼承基底 Illuminate\Support\Facades\Facade 類並實現一個方法:getFacadeAccessor返回名稱。

自定義Facade

參考

Step 1 −創建一個名為 TestFacadesServiceProvider的ServiceProvider ,使用如下命令即可:

php artisan make:provider TestFacadesServiceProvider

Step 2 − 創建一個底層代理類,命名為“TestFacades.php” at “App/Test”.

App/Test/TestFacades.php

<?php

namespace App\Test;

class TestFacades{

   public function testingFacades(){

      echo "Testing the Facades in Laravel.";

   }

}

?>

  

Step 3 − 創建一個 Facade 類 called “TestFacades.php” at “App/Test/Facades”.

App/Test/Facades/TestFacades.php

<?php

namespace app\Test\Facades;

use Illuminate\Support\Facades\Facade;

class TestFacades extends Facade{

   protected static function getFacadeAccessor() { return 'test'; }

}

  

Step 4 −創建一個ServiceProviders類,名為“TestFacadesServiceProviders.php” at “App/Test/Facades”.

App/Providers/TestFacadesServiceProviders.php

<?php
namespace App\Providers;
use App;
use Illuminate\Support\ServiceProvider;
class TestFacadesServiceProvider extends ServiceProvider {
 public function boot() {
 //
 }
 public function register() {
 //可以這麼綁定,這需要use App;
 //  App::bind('test',function() {
 //     return new \App\Test\TestFacades;
 //  });
  
 //也可以這麼綁定,推薦。這個test對應於Facade的getFacadeAccessor返回值
 $this->app->bind("test", function(){
 return new MyFoo(); //給這個Facade返回一個代理實例。所有對Facade的調用都會被轉發到該類對象下。
 });
 }
}

  

Step 5 − 在config/app.php註冊ServiceProvider類

Step 6 − 在config/app.php註冊自定義Facade的別名

使用測試:

Add the following lines in app/Http/routes.php.

Route::get('/facadeex', function(){
 return TestFacades::testingFacades();
});

  

Step 9 − Visit the following URL to test the Facade.

http://localhost:8000/facadeex去查看輸出

更多學習內容請訪問:

騰訊T3-T4標準精品PHP架構師教程目錄大全,只要你看完保證薪資上升一個臺階(持續更新)圖標

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 值多態是一種介於傳統多態與類型擦除之間的多態實現方式,借鑒了值語義,保留了繼承,在單繼承的適用範圍內,程式和程式員都能從中受益。 ...
  • 泛型數組列表 為什麼要使用泛型數組列表 使用常規數組,界限固定,不易擴展。 int[]nums =new int[size]; 這個數組的長度固定為了size的大小。但如果使用數組列表就可以自動開闢空間,存放元素。 泛型數組列表ArrayList的定義 1.無參的 ArrayList integer ...
  • [toc] 1、分析網頁 當我們去爬取網頁時,首先要做的就是先分析網頁結構,然後就會發現相應的規律,如下所示: 生成鏈接:從網頁鏈接的規律中可得寫一個for迴圈即可生成它的鏈接,其中它的間隔為25,程式如下: 得到的結果如下: 2、請求伺服器 在爬取網頁之前,我們要向伺服器發出請求 2.1導入包 沒 ...
  • 前言 文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。 PS:如有需要Python學習資料的小伙伴可以加點擊下方鏈接自行獲取http://t.cn/A6Zvjdun 最近找工作,爬蟲面試的一個面試題。涉及的反爬還是比較全面的,結果公 ...
  • 數據分析當中讀取本地數據,txt,excel,csv,json,SQLite,SqLite_json等數據類型 ...
  • 大家在學習java多線程的時候肯定會遇到這個問題,而且在面試的時候也可能會談到java多線程這一塊的知識。今天我們就來看看這個東西~~~ synchronized 這個是對類實例進行加鎖,可以簡稱為“實例鎖”或者是“對象鎖”。當某個線程調用synchronized方法的時候,就會給它加上了一個鎖,其 ...
  • 我的LeetCode:https://leetcode cn.com/u/ituring/ 我的LeetCode刷題源碼[GitHub]:https://github.com/izhoujie/Algorithmcii LeetCode 542. 01 矩陣 題目 給定一個由 0 和 1 組成的矩陣 ...
  • 在控制台模擬操作cmd 我們設計簡單的程式實現以下功能 1.cd顯示當前目錄的名稱或將其更改。 2.date顯示時間 3.md 創建一個目錄 4. rd 刪除目錄 5.dir 顯示一個目錄中的文件和子目錄 6 help 提示操作 代碼 先在項目下創建一個help.txt文件,內容從cmd的help中 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...