14

I'm confused by the Facades offered by Laravel.

The Laravel documentation states:

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.

Please help me to understand:

  1. Why we really use use Illuminate\Support\Facades?
  2. How to create custom Facades ?
4

3 に答える 3

5

一般的に言えば、ファサード (/fəˈsɑːd/ と発音) は、建物またはその他のものの外側および正面を向いている側です。ファサードの重要性は、気づきやすく、より目立つことです。同様に、laravel にもファサードの概念があります。これは、コードの読みやすさを管理し、関数とクラスの構文を覚えやすくするために使用されます。

Laravel ファサードは、サービス コンテナー内のサービスに静的なようなインターフェイスを提供するクラスです。これらは、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'));
});

上記の例の方が洗練されていて、構文が覚えやすいと思いませんか? それがファサードの美しさです。

于 2019-07-27T05:49:35.957 に答える