Laravel之Contracts和Facades详解

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'                  => ['IlluminateFoundationApplication', 'IlluminateContractsContainerContainer', 'IlluminateContractsFoundationApplication'],

            'auth'                 => 'IlluminateAuthAuthManager',

            'auth.driver'          => ['IlluminateAuthGuard', 'IlluminateContractsAuthGuard'],

            'auth.password.tokens' => 'IlluminateAuthPasswordsTokenRepositoryInterface',

            'blade.compiler'       => 'IlluminateViewCompilersBladeCompiler',

            'cache'                => ['IlluminateCacheCacheManager', 'IlluminateContractsCacheFactory'],

            'cache.store'          => ['IlluminateCacheRepository', 'IlluminateContractsCacheRepository'],

            'config'               => ['IlluminateConfigRepository', 'IlluminateContractsConfigRepository'],

            'cookie'               => ['IlluminateCookieCookieJar', 'IlluminateContractsCookieFactory', 'IlluminateContractsCookieQueueingFactory'],

            'encrypter'            => ['IlluminateEncryptionEncrypter', 'IlluminateContractsEncryptionEncrypter'],

            'db'                   => 'IlluminateDatabaseDatabaseManager',

            'db.connection'        => ['IlluminateDatabaseConnection', 'IlluminateDatabaseConnectionInterface'],

            'events'               => ['IlluminateEventsDispatcher', 'IlluminateContractsEventsDispatcher'],

            'files'                => 'IlluminateFilesystemFilesystem',

            'filesystem'           => ['IlluminateFilesystemFilesystemManager', 'IlluminateContractsFilesystemFactory'],

            'filesystem.disk'      => 'IlluminateContractsFilesystemFilesystem',

            'filesystem.cloud'     => 'IlluminateContractsFilesystemCloud',

            'hash'                 => 'IlluminateContractsHashingHasher',

            'translator'           => ['IlluminateTranslationTranslator', 'SymfonyComponentTranslationTranslatorInterface'],

            'log'                  => ['IlluminateLogWriter', 'IlluminateContractsLoggingLog', 'PsrLogLoggerInterface'],

            'mailer'               => ['IlluminateMailMailer', 'IlluminateContractsMailMailer', 'IlluminateContractsMailMailQueue'],

            'auth.password'        => ['IlluminateAuthPasswordsPasswordBroker', 'IlluminateContractsAuthPasswordBroker'],

            'queue'                => ['IlluminateQueueQueueManager', 'IlluminateContractsQueueFactory', 'IlluminateContractsQueueMonitor'],

            'queue.connection'     => 'IlluminateContractsQueueQueue',

            'redirect'             => 'IlluminateRoutingRedirector',

            'redis'                => ['IlluminateRedisDatabase', 'IlluminateContractsRedisDatabase'],

            'request'              => 'IlluminateHttpRequest',

            'router'               => ['IlluminateRoutingRouter', 'IlluminateContractsRoutingRegistrar'],

            'session'              => 'IlluminateSessionSessionManager',

            'session.store'        => ['IlluminateSessionStore', 'SymfonyComponentHttpFoundationSessionSessionInterface'],

            'url'                  => ['IlluminateRoutingUrlGenerator', 'IlluminateContractsRoutingUrlGenerator'],

            'validator'            => ['IlluminateValidationFactory', 'IlluminateContractsValidationFactory'],

            'view'                 => ['IlluminateViewFactory', 'IlluminateContractsViewFactory'],

        ];

  

在我们自定义的接口实现时,我们可以在ServiceProvider中使用进行绑定:

$this->app->bind('AppContractsEventPusher', 'AppServicesPusherEventPusher');

  

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'       => IlluminateSupportFacadesApp::class,

        'Artisan'   => IlluminateSupportFacadesArtisan::class,

        'Auth'      => IlluminateSupportFacadesAuth::class,

        'Blade'     => IlluminateSupportFacadesBlade::class,

        'Bus'       => IlluminateSupportFacadesBus::class,

        'Cache'     => IlluminateSupportFacadesCache::class,

        'Config'    => IlluminateSupportFacadesConfig::class,

        'Cookie'    => IlluminateSupportFacadesCookie::class,

        'Crypt'     => IlluminateSupportFacadesCrypt::class,

        'DB'        => IlluminateSupportFacadesDB::class,

        'Eloquent'  => IlluminateDatabaseEloquentModel::class,

        'Event'     => IlluminateSupportFacadesEvent::class,

        'File'      => IlluminateSupportFacadesFile::class,

        'Gate'      => IlluminateSupportFacadesGate::class,

        'Hash'      => IlluminateSupportFacadesHash::class,

        'Input'     => IlluminateSupportFacadesInput::class,

        'Lang'      => IlluminateSupportFacadesLang::class,

        'Log'       => IlluminateSupportFacadesLog::class,

        'Mail'      => IlluminateSupportFacadesMail::class,

        'Password'  => IlluminateSupportFacadesPassword::class,

        'Queue'     => IlluminateSupportFacadesQueue::class,

        'Redirect'  => IlluminateSupportFacadesRedirect::class,

        'Redis'     => IlluminateSupportFacadesRedis::class,

        'Request'   => IlluminateSupportFacadesRequest::class,

        'Response'  => IlluminateSupportFacadesResponse::class,

        'Route'     => IlluminateSupportFacadesRoute::class,

        'Schema'    => IlluminateSupportFacadesSchema::class,

        'Session'   => IlluminateSupportFacadesSession::class,

        'Storage'   => IlluminateSupportFacadesStorage::class,

        'URL'       => IlluminateSupportFacadesURL::class,

        'Validator' => IlluminateSupportFacadesValidator::class,

        'View'      => IlluminateSupportFacadesView::class,

    ],

  

你是不是发现了什么?对,Facades其实就是在config/app.php中定义的一系列类的别名。只不过这些类都具有一个共同的特点,那就是继承基底 IlluminateSupportFacadesFacade 类并实现一个方法:getFacadeAccessor返回名称。

自定义Facade

参考

Step 1 −创建一个名为 TestFacadesServiceProvider的ServiceProvider ,使用如下命令即可:

php artisan make:provider TestFacadesServiceProvider

Step 2 − 创建一个底层代理类,命名为“TestFacades.php” at “App/Test”.

App/Test/TestFacades.php

<?php

namespace AppTest;

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 appTestFacades;

use IlluminateSupportFacadesFacade;

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 AppProviders;
use App;
use IlluminateSupportServiceProvider;
class TestFacadesServiceProvider extends ServiceProvider {
 public function boot() {
 //
 }
 public function register() {
 //可以这么绑定,这需要use App;
 //  App::bind('test',function() {
 //     return new AppTestTestFacades;
 //  });
  
 //也可以这么绑定,推荐。这个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架构师教程目录大全,只要你看完保证薪资上升一个台阶(持续更新)图标

原文地址:https://www.cnblogs.com/a609251438/p/12707971.html