Home  >  Article  >  PHP Framework  >  Detailed explanation of Contracts and Facades in Laravel

Detailed explanation of Contracts and Facades in Laravel

藏色散人
藏色散人forward
2020-04-15 13:42:463404browse

Contracts

Contracts actually advocates interface-oriented programming to achieve the purpose of decoupling. These common interfaces have been designed for you by Laravel. These are Contracts.

So how does Laravel know which implementation we need to use?

In Laravel's default Contracts binding, there is such a definition in 'Illuminate/Foundation/Application.php': This is the binding of the default interface implementation.

Recommendation: "laravel tutorial

/**
     * 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'],
        ];

When implementing our custom interface, we can use it in ServiceProvider for binding:

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

Facades

Facades provide a "static" interface for classes available in the application's service container. Laravel "facades" act as "static proxies" for base classes within the service container. Difficult to understand?

We open config/app.php in the project directory and find

/*
    |--------------------------------------------------------------------------
    | 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,
    ],

Did you find anything? Yes, Facades are actually aliases for a series of classes defined in config/app.php. But these classes all have a common feature, which is to inherit the base Illuminate\Support\Facades\Facade class and implement a method: getFacadeAccessor returns the name.

Customized Facade

Reference http://www.tutorialspoint.com/laravel/laravel_facades.htm

Step 1 −Create a ServiceProvider named TestFacadesServiceProvider, use the following command:

php artisan make:provider TestFacadesServiceProvider

Step 2 − Create an underlying proxy class and name it Create a Facade class called “TestFacades.php” for “TestFacades.php” at “App/Test”. php” at “App/Test/Facades”.

App/Test/Facades/TestFacades.php

<?php
namespace App\Test;
class TestFacades{
   public function testingFacades(){
      echo "Testing the Facades in Laravel.";
   }
}
?>

Step 4 −Create a ServiceProviders class named “ TestFacadesServiceProviders.php” at “App/Test/Facades”.

App/Providers/TestFacadesServiceProviders.php

<?php
namespace app\Test\Facades;
use Illuminate\Support\Facades\Facade;
class TestFacades extends Facade{
   protected static function getFacadeAccessor() { return &#39;test&#39;; }
}

Step 5 − Register ServiceProvider in config/app.php Class

Step 6

− Register the custom Facade alias in config/app.phpUse test:

Add the following lines in app/ Http/routes.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(&#39;test&#39;,function() {
    //     return new \App\Test\TestFacades;
    //  });
     
     //也可以这么绑定,推荐。这个test对应于Facade的getFacadeAccessor返回值
        $this->app->bind("test", function(){
            return new MyFoo(); //给这个Facade返回一个代理实例。所有对Facade的调用都会被转发到该类对象下。
        });
   }
}

Step 9

− Visit the following URL to test the Facade.

http://localhost:8000/facadeex to view the output

The above is the detailed content of Detailed explanation of Contracts and Facades in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete