# Facades

- [Introduction](#introduction)
- [When to Utilize Facades](#when-to-use-facades)
    - [Facades vs. Dependency Injection](#facades-vs-dependency-injection)
    - [Facades vs. Helper Functions](#facades-vs-helper-functions)
- [How Facades Work](#how-facades-work)
- [Real-Time Facades](#real-time-facades)
- [Facade Class Reference](#facade-class-reference)

<a name="introduction"></a>

## Introduction


Laravel のドキュメント全体を通して、ファサードを介して Laravel の機能を操作するコード例が登場します。ファサードは、アプリケーションの [service container](/ja/php/docs/container/) で利用できるクラスに対して、「静的」なインターフェイスを提供します。Laravel には多数のファサードが用意されており、Laravel のほぼすべての機能にアクセスできます。


Laravel ファサードは、サービスコンテナ内の基礎となるクラスに対する「静的プロキシ」として機能し、従来の静的メソッドよりも高いテスト容易性と柔軟性を維持しながら、簡潔で表現力豊かな構文の利点を提供します。ファサードがどのように機能するかを完全に理解していなくても、まったく問題ありません。流れに身を任せて、Laravel について学び続けてください。


Laravel のファサードはすべて、`Illuminate\Support\Facades` 名前空間で定義されます。したがって、次のようにしてファサードに簡単にアクセスできます。

```php
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

Route::get('/cache', function () {
    return Cache::get('key');
});
```


Laravel ドキュメント全体を通じて、例の多くはフレームワークのさまざまな機能を示すためにファサードを使用します。

<a name="helper-functions"></a>

#### Helper Functions


ファサードを補完するため、Laravel では一般的な Laravel の機能をさらに簡単に扱える、さまざまなグローバル「ヘルパ関数」を提供しています。よく使うヘルパ関数には、`view`、`response`、`url`、`config` などがあります。Laravel が提供する各ヘルパ関数については、それぞれ対応する機能のドキュメントで説明していますが、完全な一覧は専用の [helper documentation](/ja/php/docs/helpers/) で確認できます。


たとえば、`Illuminate\Support\Facades\Response` ファサードを使用して JSON 応答を生成する代わりに、単に `response` 関数を使用することもできます。ヘルパ関数はグローバルに利用できるため、使用するためにクラスをインポートする必要はありません。

```php
use Illuminate\Support\Facades\Response;

Route::get('/users', function () {
    return Response::json([
        // ...
    ]);
});

Route::get('/users', function () {
    return response()->json([
        // ...
    ]);
});
```

<a name="when-to-use-facades"></a>

## When to Utilize Facades


ファサードには多くの利点があります。これらは、手動で挿入または設定する必要がある長いクラス名を覚えなくても、Laravel の機能を使用できる簡潔で覚えやすい構文を提供します。さらに、PHP の動的メソッドを独自に使用しているため、テストが簡単です。


ただし、ファサードを使用する場合は注意が必要です。ファサードの主な危険は、クラスの「スコープクリープ」、つまり責任範囲が広がりすぎることです。ファサードは非常に使いやすく、注入の必要がないため、クラスを成長させ続けて 1 つのクラスで多くのファサードを使用することも簡単です。依存関係の注入を使用すると、大規模なコンストラクターがクラスが大きくなりすぎていることを視覚的にフィードバックすることで、この可能性が軽減されます。したがって、ファサードを使用するときは、クラスの責任範囲を狭く保つように、クラスの規模に特に注意してください。クラスが大きくなりすぎる場合は、複数の小さなクラスに分割することを検討してください。

<a name="facades-vs-dependency-injection"></a>

### Facades vs. Dependency Injection


依存注入の主な利点の 1 つは、注入されたクラスの実装を交換できることです。これは、モックまたはスタブを挿入し、スタブでさまざまなメソッドが呼び出されたことをアサートできるため、テスト中に役立ちます。


通常、真に静的なクラス メソッドをモックしたりスタブしたりすることはできません。ただし、ファサードは動的メソッドを使用して、サービスコンテナから解決されたオブジェクトへのメソッド呼び出しをプロキシするため、実際には、挿入されたクラス インスタンスをテストするのと同じようにファサードをテストできます。たとえば、次のルートがあるとします。

```php
use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
    return Cache::get('key');
});
```


Laravel のファサード テスト メソッドを使用すると、次のテストを作成して、予想した引数を使用して `Cache::get` メソッドが呼び出されたことを確認できます。

```php tab=Pest
use Illuminate\Support\Facades\Cache;

test('basic example', function () {
    Cache::shouldReceive('get')
        ->with('key')
        ->andReturn('value');

    $response = $this->get('/cache');

    $response->assertSee('value');
});
```

```php tab=PHPUnit
use Illuminate\Support\Facades\Cache;

/**
 * A basic functional test example.
 */
public function test_basic_example(): void
{
    Cache::shouldReceive('get')
        ->with('key')
        ->andReturn('value');

    $response = $this->get('/cache');

    $response->assertSee('value');
}
```

<a name="facades-vs-helper-functions"></a>

### Facades vs. Helper Functions


ファサードに加えて、Laravel には、ビューの生成、イベントの起動、ジョブのディスパッチ、HTTP 応答の送信などの一般的なタスクを実行できるさまざまな「ヘルパ」関数が含まれています。これらのヘルパ関数の多くは、対応するファサードと同じ機能を実行します。たとえば、次のファサード呼び出しとヘルパ呼び出しは同等です。

```php
return Illuminate\Support\Facades\View::make('profile');

return view('profile');
```


ファサードとヘルパ関数の間には実質的な違いはまったくありません。ヘルパ関数を使用する場合でも、対応するファサードとまったく同じようにテストできます。たとえば、次のルートがあるとします。

```php
Route::get('/cache', function () {
    return cache('key');
});
```


`cache` ヘルパは、`Cache` ファサードの基礎となるクラスで `get` メソッドを呼び出します。したがって、ヘルパ関数を使用している場合でも、次のテストを作成して、メソッドが予期した引数で呼び出されたことを確認できます。

```php
use Illuminate\Support\Facades\Cache;

/**
 * A basic functional test example.
 */
public function test_basic_example(): void
{
    Cache::shouldReceive('get')
        ->with('key')
        ->andReturn('value');

    $response = $this->get('/cache');

    $response->assertSee('value');
}
```

<a name="how-facades-work"></a>

## How Facades Work


Laravel アプリケーションでは、ファサードはコンテナからオブジェクトへのアクセスを提供するクラスです。これを実現する仕組みは、`Facade` クラスにあります。 Laravel のファサード、および作成するカスタム ファサードは、基本 `Illuminate\Support\Facades\Facade` クラスを拡張します。


`Facade` 基本クラスは、`__callStatic()` マジック メソッドを利用して、ファサードへの呼び出しを、コンテナから解決されたオブジェクトに委譲します。以下の例では、Laravel キャッシュ システムへの呼び出しが行われます。このコードを一目見ると、静的 `get` メソッドが `Cache` クラスで呼び出されていると思われるかもしれません。

```php
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     */
    public function showProfile(string $id): View
    {
        $user = Cache::get('user:'.$id);

        return view('profile', ['user' => $user]);
    }
}
```


ファイルの先頭近くで、`Cache` ファサードを「インポート」していることに注目してください。このファサードは、`Illuminate\Contracts\Cache\Factory` インターフェイスの基礎となる実装にアクセスするためのプロキシとして機能します。ファサードを使用して行う呼び出しはすべて、Laravel のキャッシュ サービスの基礎となるインスタンスに渡されます。


その `Illuminate\Support\Facades\Cache` クラスを見ると、静的メソッド `get` がないことがわかります。

```php
class Cache extends Facade
{
    /**
     * Get the registered name of the component.
     */
    protected static function getFacadeAccessor(): string
    {
        return 'cache';
    }
}
```


その代わりに、`Cache` ファサードは基底の `Facade` クラスを拡張し、`getFacadeAccessor()` メソッドを定義します。このメソッドは、サービスコンテナのバインド名を返します。`Cache` ファサードの静的メソッドを参照すると、Laravel は [service container](/ja/php/docs/container/) から `cache` バインドを解決し、そのオブジェクトに対して要求されたメソッド（この場合は `get`）を実行します。

<a name="real-time-facades"></a>

## Real-Time Facades


リアルタイム ファサードを使用すると、アプリケーション内の任意のクラスをファサードであるかのように扱うことができます。これがどのように使用できるかを説明するために、まずリアルタイム ファサードを使用しないコードを調べてみましょう。たとえば、`Podcast` モデルに `publish` メソッドがあると仮定します。ただし、ポッドキャストを公開するには、`Publisher` インスタンスを挿入する必要があります。

```php
<?php

namespace App\Models;

use App\Contracts\Publisher;
use Illuminate\Database\Eloquent\Model;

class Podcast extends Model
{
    /**
     * Publish the podcast.
     */
    public function publish(Publisher $publisher): void
    {
        $this->update(['publishing' => now()]);

        $publisher->publish($this);
    }
}
```


パブリッシャー実装をメソッドに挿入すると、挿入されたパブリッシャーをモックできるため、メソッドを分離して簡単にテストできます。ただし、`publish` メソッドを呼び出すたびに、常にパブリッシャー インスタンスを渡す必要があります。リアルタイム ファサードを使用すると、`Publisher` インスタンスを明示的に渡す必要がなく、同じテスト容易性を維持できます。リアルタイム ファサードを生成するには、インポートされたクラスの名前空間に `Facades` というプレフィックスを付けます。

```php
<?php

namespace App\Models;

use App\Contracts\Publisher; // [tl! remove]
use Facades\App\Contracts\Publisher; // [tl! add]
use Illuminate\Database\Eloquent\Model;

class Podcast extends Model
{
    /**
     * Publish the podcast.
     */
    public function publish(Publisher $publisher): void // [tl! remove]
    public function publish(): void // [tl! add]
    {
        $this->update(['publishing' => now()]);

        $publisher->publish($this); // [tl! remove]
        Publisher::publish($this); // [tl! add]
    }
}
```


リアルタイム ファサードが使用される場合、パブリッシャーの実装は、`Facades` プレフィックスの後に表示されるインターフェイスまたはクラス名の一部を使用して、サービスコンテナーから解決されます。テストするときは、Laravel の組み込みファサード テスト ヘルパを使用して、このメソッド呼び出しをモックできます。

```php tab=Pest
<?php

use App\Models\Podcast;
use Facades\App\Contracts\Publisher;
use Illuminate\Foundation\Testing\RefreshDatabase;

pest()->use(RefreshDatabase::class);

test('podcast can be published', function () {
    $podcast = Podcast::factory()->create();

    Publisher::shouldReceive('publish')->once()->with($podcast);

    $podcast->publish();
});
```

```php tab=PHPUnit
<?php

namespace Tests\Feature;

use App\Models\Podcast;
use Facades\App\Contracts\Publisher;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PodcastTest extends TestCase
{
    use RefreshDatabase;

    /**
     * A test example.
     */
    public function test_podcast_can_be_published(): void
    {
        $podcast = Podcast::factory()->create();

        Publisher::shouldReceive('publish')->once()->with($podcast);

        $podcast->publish();
    }
}
```

<a name="facade-class-reference"></a>

## Facade Class Reference


以下に、すべてのファサードと、それらの基盤となるクラスを示します。特定のファサードのルートに対応する API ドキュメントをすばやく調べるのに便利です。該当する場合は、[service container binding](/ja/php/docs/container/) キーも記載しています。

<div class="overflow-auto">


| ファサード | クラス | サービスコンテナのバインディング |
| --- | --- | --- |
| App | [Illuminate\Foundation\Application](https://api.laravel.com/docs/13.x/Illuminate/Foundation/Application.html) | `app` |
| Artisan | [Illuminate\Contracts\Console\Kernel](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Console/Kernel.html) | &nbsp; |
| Auth (Instance) | [Illuminate\Contracts\Auth\Guard](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Auth/Guard.html) | `auth.driver` |
| Auth | [Illuminate\Auth\AuthManager](https://api.laravel.com/docs/13.x/Illuminate/Auth/AuthManager.html) | `auth` |
| Blade | [Illuminate\View\Compilers\BladeCompiler](https://api.laravel.com/docs/13.x/Illuminate/View/Compilers/BladeCompiler.html) | `blade.compiler` |
| Broadcast (Instance) | [Illuminate\Contracts\Broadcasting\Broadcaster](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Broadcasting/Broadcaster.html) | &nbsp; |
| Broadcast | [Illuminate\Contracts\Broadcasting\Factory](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Broadcasting/Factory.html) | &nbsp; |
| Bus | [Illuminate\Contracts\Bus\Dispatcher](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Bus/Dispatcher.html) | &nbsp; |
| Cache (Instance) | [Illuminate\Cache\Repository](https://api.laravel.com/docs/13.x/Illuminate/Cache/Repository.html) | `cache.store` |
| Cache | [Illuminate\Cache\CacheManager](https://api.laravel.com/docs/13.x/Illuminate/Cache/CacheManager.html) | `cache` |
| Cloud | [Illuminate\Foundation\Cloud\CloudManager](https://api.laravel.com/docs/13.x/Illuminate/Foundation/Cloud/CloudManager.html) | &nbsp; |
| Config | [Illuminate\Config\Repository](https://api.laravel.com/docs/13.x/Illuminate/Config/Repository.html) | `config` |
| Context | [Illuminate\Log\Context\Repository](https://api.laravel.com/docs/13.x/Illuminate/Log/Context/Repository.html) | &nbsp; |
| Cookie | [Illuminate\Cookie\CookieJar](https://api.laravel.com/docs/13.x/Illuminate/Cookie/CookieJar.html) | `cookie` |
| Crypt | [Illuminate\Encryption\Encrypter](https://api.laravel.com/docs/13.x/Illuminate/Encryption/Encrypter.html) | `encrypter` |
| Date | [Illuminate\Support\DateFactory](https://api.laravel.com/docs/13.x/Illuminate/Support/DateFactory.html) | `date` |
| DB (Instance) | [Illuminate\Database\Connection](https://api.laravel.com/docs/13.x/Illuminate/Database/Connection.html) | `db.connection` |
| DB | [Illuminate\Database\DatabaseManager](https://api.laravel.com/docs/13.x/Illuminate/Database/DatabaseManager.html) | `db` |
| Event | [Illuminate\Events\Dispatcher](https://api.laravel.com/docs/13.x/Illuminate/Events/Dispatcher.html) | `events` |
| Exceptions (Instance) | [Illuminate\Contracts\Debug\ExceptionHandler](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Debug/ExceptionHandler.html) | &nbsp; |
| Exceptions | [Illuminate\Foundation\Exceptions\Handler](https://api.laravel.com/docs/13.x/Illuminate/Foundation/Exceptions/Handler.html) | &nbsp; |
| File | [Illuminate\Filesystem\Filesystem](https://api.laravel.com/docs/13.x/Illuminate/Filesystem/Filesystem.html) | `files` |
| Gate | [Illuminate\Contracts\Auth\Access\Gate](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Auth/Access/Gate.html) | &nbsp; |
| Hash | [Illuminate\Contracts\Hashing\Hasher](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Hashing/Hasher.html) | `hash` |
| Http | [Illuminate\Http\Client\Factory](https://api.laravel.com/docs/13.x/Illuminate/Http/Client/Factory.html) | &nbsp; |
| Lang | [Illuminate\Translation\Translator](https://api.laravel.com/docs/13.x/Illuminate/Translation/Translator.html) | `translator` |
| Log | [Illuminate\Log\LogManager](https://api.laravel.com/docs/13.x/Illuminate/Log/LogManager.html) | `log` |
| Mail (Instance) | [Illuminate\Mail\Mailer](https://api.laravel.com/docs/13.x/Illuminate/Mail/Mailer.html) | `mailer` |
| Mail | [Illuminate\Mail\MailManager](https://api.laravel.com/docs/13.x/Illuminate/Mail/MailManager.html) | `mail.manager` |
| Notification | [Illuminate\Notifications\ChannelManager](https://api.laravel.com/docs/13.x/Illuminate/Notifications/ChannelManager.html) | &nbsp; |
| Password (Instance) | [Illuminate\Auth\Passwords\PasswordBroker](https://api.laravel.com/docs/13.x/Illuminate/Auth/Passwords/PasswordBroker.html) | `auth.password.broker` |
| Password | [Illuminate\Auth\Passwords\PasswordBrokerManager](https://api.laravel.com/docs/13.x/Illuminate/Auth/Passwords/PasswordBrokerManager.html) | `auth.password` |
| Pipeline (Instance) | [Illuminate\Pipeline\Pipeline](https://api.laravel.com/docs/13.x/Illuminate/Pipeline/Pipeline.html) | &nbsp; |
| Process | [Illuminate\Process\Factory](https://api.laravel.com/docs/13.x/Illuminate/Process/Factory.html) | &nbsp; |
| Queue (Base Class) | [Illuminate\Queue\Queue](https://api.laravel.com/docs/13.x/Illuminate/Queue/Queue.html) | &nbsp; |
| Queue (Instance) | [Illuminate\Contracts\Queue\Queue](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Queue/Queue.html) | `queue.connection` |
| Queue | [Illuminate\Queue\QueueManager](https://api.laravel.com/docs/13.x/Illuminate/Queue/QueueManager.html) | `queue` |
| RateLimiter | [Illuminate\Cache\RateLimiter](https://api.laravel.com/docs/13.x/Illuminate/Cache/RateLimiter.html) | &nbsp; |
| Redirect | [Illuminate\Routing\Redirector](https://api.laravel.com/docs/13.x/Illuminate/Routing/Redirector.html) | `redirect` |
| Redis (Instance) | [Illuminate\Redis\Connections\Connection](https://api.laravel.com/docs/13.x/Illuminate/Redis/Connections/Connection.html) | `redis.connection` |
| Redis | [Illuminate\Redis\RedisManager](https://api.laravel.com/docs/13.x/Illuminate/Redis/RedisManager.html) | `redis` |
| Request | [Illuminate\Http\Request](https://api.laravel.com/docs/13.x/Illuminate/Http/Request.html) | `request` |
| Response (Instance) | [Illuminate\Http\Response](https://api.laravel.com/docs/13.x/Illuminate/Http/Response.html) | &nbsp; |
| Response | [Illuminate\Contracts\Routing\ResponseFactory](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Routing/ResponseFactory.html) | &nbsp; |
| Route | [Illuminate\Routing\Router](https://api.laravel.com/docs/13.x/Illuminate/Routing/Router.html) | `router` |
| Schedule | [Illuminate\Console\Scheduling\Schedule](https://api.laravel.com/docs/13.x/Illuminate/Console/Scheduling/Schedule.html) | &nbsp; |
| Schema | [Illuminate\Database\Schema\Builder](https://api.laravel.com/docs/13.x/Illuminate/Database/Schema/Builder.html) | &nbsp; |
| Session (Instance) | [Illuminate\Session\Store](https://api.laravel.com/docs/13.x/Illuminate/Session/Store.html) | `session.store` |
| Session | [Illuminate\Session\SessionManager](https://api.laravel.com/docs/13.x/Illuminate/Session/SessionManager.html) | `session` |
| Storage (Instance) | [Illuminate\Contracts\Filesystem\Filesystem](https://api.laravel.com/docs/13.x/Illuminate/Contracts/Filesystem/Filesystem.html) | `filesystem.disk` |
| Storage | [Illuminate\Filesystem\FilesystemManager](https://api.laravel.com/docs/13.x/Illuminate/Filesystem/FilesystemManager.html) | `filesystem` |
| URL | [Illuminate\Routing\UrlGenerator](https://api.laravel.com/docs/13.x/Illuminate/Routing/UrlGenerator.html) | `url` |
| Validator (Instance) | [Illuminate\Validation\Validator](https://api.laravel.com/docs/13.x/Illuminate/Validation/Validator.html) | &nbsp; |
| Validator | [Illuminate\Validation\Factory](https://api.laravel.com/docs/13.x/Illuminate/Validation/Factory.html) | `validator` |
| View (Instance) | [Illuminate\View\View](https://api.laravel.com/docs/13.x/Illuminate/View/View.html) | &nbsp; |
| View | [Illuminate\View\Factory](https://api.laravel.com/docs/13.x/Illuminate/View/Factory.html) | `view` |
| Vite | [Illuminate\Foundation\Vite](https://api.laravel.com/docs/13.x/Illuminate/Foundation/Vite.html) | &nbsp; |

</div>