Readouble

Laravel 10.x キャッシュ

イントロダクションIntroduction

アプリケーションによって実行されるデータ取得または処理タスクの一部は、CPUに負荷がかかるか、完了するまでに数秒かかる場合があります。この場合、取得したデータを一時的にキャッシュして、同じデータに対する後続のリクエストですばやく取得できるようにするのが一般的です。キャッシュするデータは通常、MemcachedRedisなどの非常に高速なデータストアに保存します。Some of the data retrieval or processing tasks performed by your application could be CPU intensive or take several seconds to complete. When this is the case, it is common to cache the retrieved data for a time so it can be retrieved quickly on subsequent requests for the same data. The cached data is usually stored in a very fast data store such as Memcached[https://memcached.org] or Redis[https://redis.io].

幸いLaravelはさまざまなキャッシュバックエンドに表現力豊かで統一されたAPIを提供し、その超高速データ取得を利用してWebアプリケーションを高速化できるようにします。Thankfully, Laravel provides an expressive, unified API for various cache backends, allowing you to take advantage of their blazing fast data retrieval and speed up your web application.

設定Configuration

アプリケーションのキャッシュ設定ファイルはconfig/cache.phpにあります。このファイルでは、アプリケーション全体でデフォルトで使用するキャッシュドライバを指定します。Laravelは、MemcachedRedisDynamoDBなどの一般的なキャッシュバックエンドとリレーショナルデータベースをはじめからサポートしています。さらに、ファイルベースのキャッシュドライバも利用可能で、arrayおよび「null」キャッシュドライバは、自動テストに便利なキャッシュバックエンドを提供します。Your application's cache configuration file is located at config/cache.php. In this file, you may specify which cache driver you would like to be used by default throughout your application. Laravel supports popular caching backends like Memcached[https://memcached.org], Redis[https://redis.io], DynamoDB[https://aws.amazon.com/dynamodb], and relational databases out of the box. In addition, a file based cache driver is available, while array and "null" cache drivers provide convenient cache backends for your automated tests.

キャッシュ設定ファイルには、ファイル内のコメントで説明しているさまざまな他のオプションも存在しているため、これらのオプションを必ずお読みください。デフォルトでLaravelは、シリアルライズ後にオブジェクトをサーバのファイルシステムにキャッシュするfileキャッシュドライバを使用するように設定しています。大規模なアプリケーションの場合は、MemcachedやRedisなどのより堅牢なドライバを使用することをおすすめします。同じドライバに対して複数のキャッシュ設定を構築することもできます。The cache configuration file also contains various other options, which are documented within the file, so make sure to read over these options. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects on the server's filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver.

ドライバ要件Driver Prerequisites

データベースDatabase

databaseキャッシュドライバを使用する場合は、キャッシュアイテムを格納するためのテーブルを用意する必要があります。以下は、そのテーブルのためのSchema定義の例です。When using the database cache driver, you will need to set up a table to contain the cache items. You'll find an example Schema declaration for the table below:

Schema::create('cache', function (Blueprint $table) {
    $table->string('key')->unique();
    $table->text('value');
    $table->integer('expiration');
});

lightbulb Note: php artisan cache:table Artisanコマンドを使用して、適切なスキーマのマイグレーションを生成することもできます。[!NOTE]
You may also use the php artisan cache:table Artisan command to generate a migration with the proper schema.

MemcachedMemcached

Memcachedドライバを使用するには、Memcached PECLパッケージがインストールされている必要があります。すべてのMemcachedサーバをconfig/cache.php設定ファイルにリストしてください。このファイルには、設定しやすいようにmemcached.serversエントリがはじめから用意しています。Using the Memcached driver requires the Memcached PECL package[https://pecl.php.net/package/memcached] to be installed. You may list all of your Memcached servers in the config/cache.php configuration file. This file already contains a memcached.servers entry to get you started:

'memcached' => [
    'servers' => [
        [
            'host' => env('MEMCACHED_HOST', '127.0.0.1'),
            'port' => env('MEMCACHED_PORT', 11211),
            'weight' => 100,
        ],
    ],
],

必要に応じて、hostオプションをUNIXソケットパスに設定できます。これを行う場合は、portオプションを0に設定する必要があります。If needed, you may set the host option to a UNIX socket path. If you do this, the port option should be set to 0:

'memcached' => [
    [
        'host' => '/var/run/memcached/memcached.sock',
        'port' => 0,
        'weight' => 100
    ],
],

RedisRedis

LaravelでRedisキャッシュを使用する前に、PECLを介してPhpRedis PHP拡張機能をインストールするか、Composerを介してpredis/predisパッケージ(〜1.0)をインストールする必要があります。Laravel Sailにはすでにこの拡張機能が含まれています。さらに、Laravel ForgeLaravel Vaporなどの公式のLaravel開発プラットフォームには、デフォルトでPhpRedis拡張機能がインストールされています。Before using a Redis cache with Laravel, you will need to either install the PhpRedis PHP extension via PECL or install the predis/predis package (~1.0) via Composer. Laravel Sail[/docs/{{version}}/sail] already includes this extension. In addition, official Laravel deployment platforms such as Laravel Forge[https://forge.laravel.com] and Laravel Vapor[https://vapor.laravel.com] have the PhpRedis extension installed by default.

Redisの設定の詳細については、Laravelドキュメントページを参照してください。For more information on configuring Redis, consult its Laravel documentation page[/docs/{{version}}/redis#configuration].

DynamoDBDynamoDB

DynamoDBキャッシュドライバを使用する前に、すべてのキャッシュデータを格納するためのDynamoDBテーブルを作成する必要があります。通常、このテーブルはcacheという名前です。ただし、アプリケーションのcache設定ファイル内のstores.dynamodb.table設定値の値に基づいてテーブルに名前を付ける必要があります。Before using the DynamoDB[https://aws.amazon.com/dynamodb] cache driver, you must create a DynamoDB table to store all of the cached data. Typically, this table should be named cache. However, you should name the table based on the value of the stores.dynamodb.table configuration value within your application's cache configuration file.

このテーブルには、アプリケーションのcache設定ファイル内のstores.dynamodb.attributes.key設定項目の値に対応する名前の、文字列パーティションキーもあります。デフォルトでは、パーティションキーはkeyという名前にする必要があります。This table should also have a string partition key with a name that corresponds to the value of the stores.dynamodb.attributes.key configuration item within your application's cache configuration file. By default, the partition key should be named key.

キャッシュ使用法Cache Usage

キャッシュインスタンスの取得Obtaining a Cache Instance

キャッシュ保存域インスタンスを取得するには、Cacheファサードを使用できます。これは、このドキュメント全体で使用します。Cacheファサードは、Laravelキャッシュ契約の基盤となる実装への便利で簡潔なアクセスを提供します。To obtain a cache store instance, you may use the Cache facade, which is what we will use throughout this documentation. The Cache facade provides convenient, terse access to the underlying implementations of the Laravel cache contracts:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;

class UserController extends Controller
{
    /**
     * アプリケーションのすべてのユーザーのリストを表示
     */
    public function index(): array
    {
        $value = Cache::get('key');

        return [
            // ...
        ];
    }
}

複数のキャッシュ保存域へのアクセスAccessing Multiple Cache Stores

Cacheファサードを使用すると、storeメソッドを介してさまざまなキャッシュ保存域にアクセスできます。storeメソッドに渡されるキーは、cache設定ファイルのstores設定配列にリストされている保存域の1つに対応している必要があります。Using the Cache facade, you may access various cache stores via the store method. The key passed to the store method should correspond to one of the stores listed in the stores configuration array in your cache configuration file:

$value = Cache::store('file')->get('foo');

Cache::store('redis')->put('bar', 'baz', 600); // 10分

キャッシュからのアイテム取得Retrieving Items From the Cache

Cacheファサードのgetメソッドは、キャッシュからアイテムを取得するために使用します。アイテムがキャッシュに存在しない場合、nullを返します。必要に応じて、アイテムが存在しない場合に返されるデフォルト値を指定する2番目の引数をgetメソッドに渡すことができます。The Cache facade's get method is used to retrieve items from the cache. If the item does not exist in the cache, null will be returned. If you wish, you may pass a second argument to the get method specifying the default value you wish to be returned if the item doesn't exist:

$value = Cache::get('key');

$value = Cache::get('key', 'default');

デフォルト値としてクロージャを渡すこともできます。指定されたアイテムがキャッシュに存在しない場合、クロージャの結果が返されます。クロージャを渡すことで、データベースまたは他の外部サービスからのデフォルト値の取得を延期できるようになります。You may even pass a closure as the default value. The result of the closure will be returned if the specified item does not exist in the cache. Passing a closure allows you to defer the retrieval of default values from a database or other external service:

$value = Cache::get('key', function () {
    return DB::table(/* ... */)->get();
});

アイテムの存在を判定Determining Item Existence

hasメソッドを使用して、アイテムがキャッシュに存在するかを判定できます。このメソッドは、アイテムが存在するがその値がnullの場合にも、falseを返します。The has method may be used to determine if an item exists in the cache. This method will also return false if the item exists but its value is null:

if (Cache::has('key')) {
    // ...
}

値の増減Incrementing / Decrementing Values

incrementメソッドとdecrementメソッドを使用して、キャッシュ内の整数項目の値を増減できます。これらのメソッドは両方とも、アイテムの値をインクリメントまたはデクリメントする数を示すオプションの2番目の引数を取ります。The increment and decrement methods may be used to adjust the value of integer items in the cache. Both of these methods accept an optional second argument indicating the amount by which to increment or decrement the item's value:

// 存在しない場合、値を初期設定
Cache::add('key', 0, now()->addHours(4));

// 値の増分と減分
Cache::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);

取得か保存Retrieve and Store

時に、キャッシュからアイテムを取得したいが、リクエストされたアイテムが存在しない場合はデフォルト値を保存したい場合があります。たとえば、すべてのユーザーをキャッシュから取得するか、存在しない場合はデータベースから取得してキャッシュに追加できます。これは、Cache::rememberメソッドを使用して行えます。Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn't exist. For example, you may wish to retrieve all users from the cache or, if they don't exist, retrieve them from the database and add them to the cache. You may do this using the Cache::remember method:

$value = Cache::remember('users', $seconds, function () {
    return DB::table('users')->get();
});

アイテムがキャッシュに存在しない場合、rememberメソッドに渡されたクロージャが実行され、その結果がキャッシュに配置されます。If the item does not exist in the cache, the closure passed to the remember method will be executed and its result will be placed in the cache.

rememberForeverメソッドを使用して、キャッシュからアイテムを取得するか、アイテムが存在しない場合は永久に保存できます。You may use the rememberForever method to retrieve an item from the cache or store it forever if it does not exist:

$value = Cache::rememberForever('users', function () {
    return DB::table('users')->get();
});

Retrieve and DeleteRetrieve and Delete

キャッシュからアイテムを取得してからアイテムを削除する必要がある場合は、pullメソッドを使用できます。getメソッドと同様に、アイテムがキャッシュに存在しない場合はnullが返されます。If you need to retrieve an item from the cache and then delete the item, you may use the pull method. Like the get method, null will be returned if the item does not exist in the cache:

$value = Cache::pull('key');

キャッシュへのアイテム保存Storing Items in the Cache

Cacheファサードでputメソッドを使用して、アイテムをキャッシュに保存できます。You may use the put method on the Cache facade to store items in the cache:

Cache::put('key', 'value', $seconds = 10);

保存時間がputメソッドに渡されない場合、アイテムは無期限に保存されます。If the storage time is not passed to the put method, the item will be stored indefinitely:

Cache::put('key', 'value');

秒数を整数として渡す代わりに、キャッシュするアイテムの有効期限を表すDateTimeインスタンスを渡すこともできます。Instead of passing the number of seconds as an integer, you may also pass a DateTime instance representing the desired expiration time of the cached item:

Cache::put('key', 'value', now()->addMinutes(10));

存在しない場合は保存Store if Not Present

addメソッドは、アイテムがキャッシュストアにまだ存在しない場合にのみ、アイテムをキャッシュに追加します。アイテムが実際にキャッシュに追加された場合、メソッドはtrueを返します。それ以外の場合にメソッドはfalseを返します。addメソッドはアトミック操作です。The add method will only add the item to the cache if it does not already exist in the cache store. The method will return true if the item is actually added to the cache. Otherwise, the method will return false. The add method is an atomic operation:

Cache::add('key', 'value', $seconds);

アイテムを永久に保存Storing Items Forever

foreverメソッドを使用して、アイテムをキャッシュに永続的に保存できます。保存アイテムは期限切れにならないため、forgetメソッドを使用して手作業でキャッシュから削除する必要があります。The forever method may be used to store an item in the cache permanently. Since these items will not expire, they must be manually removed from the cache using the forget method:

Cache::forever('key', 'value');

lightbulb Note: Memcachedドライバを使用している場合、「永久に」保存されているアイテムは、キャッシュがサイズ制限に達すると削除される可能性があります。[!NOTE]
If you are using the Memcached driver, items that are stored "forever" may be removed when the cache reaches its size limit.

キャッシュからのアイテム削除Removing Items From the Cache

forgetメソッドを使用してキャッシュからアイテムを削除できます。You may remove items from the cache using the forget method:

Cache::forget('key');

有効期限の秒数をゼロまたは負にすることで、アイテムを削除することもできます。You may also remove items by providing a zero or negative number of expiration seconds:

Cache::put('key', 'value', 0);

Cache::put('key', 'value', -5);

flushメソッドを使用してキャッシュ全体をクリアできます。You may clear the entire cache using the flush method:

Cache::flush();

warning Warning! キャッシュのフラッシュは、設定したキャッシュの「プレフィックス」を尊重せず、キャッシュからすべてのエントリを削除します。他のアプリケーションと共有するキャッシュをクリアするときは、これを慎重に検討してください。[!WARNING]
Flushing the cache does not respect your configured cache "prefix" and will remove all entries from the cache. Consider this carefully when clearing a cache which is shared by other applications.

キャッシュヘルパThe Cache Helper

Cacheファサードの使用に加え、グローバルなcache関数を使用して、キャッシュによるデータの取得および保存もできます。cache関数が単一の文字列引数で呼び出されると、指定されたキーの値を返します。In addition to using the Cache facade, you may also use the global cache function to retrieve and store data via the cache. When the cache function is called with a single, string argument, it will return the value of the given key:

$value = cache('key');

キーと値のペアの配列と有効期限を関数に指定すると、指定された期間、値がキャッシュに保存されます。If you provide an array of key / value pairs and an expiration time to the function, it will store values in the cache for the specified duration:

cache(['key' => 'value'], $seconds);

cache(['key' => 'value'], now()->addMinutes(10));

cache関数を引数なしで呼び出すと、Illuminate\Contracts\Cache\Factory実装のインスタンスが返され、他のキャッシュメソッドを呼び出せます。When the cache function is called without any arguments, it returns an instance of the Illuminate\Contracts\Cache\Factory implementation, allowing you to call other caching methods:

cache()->remember('users', $seconds, function () {
    return DB::table('users')->get();
});

lightbulb Note: グローバルなcache関数の呼び出しをテストするときは、ファサードをテストするのようにCache::shouldReceiveメソッドを使用できます。[!NOTE]
When testing call to the global cache function, you may use the Cache::shouldReceive method just as if you were testing the facade[/docs/{{version}}/mocking#mocking-facades].

アトミックロックAtomic Locks

warning Warning! この機能を利用するには、アプリケーションのデフォルトのキャッシュドライバとして、memcachedredisdynamodbdatabasefilearrayキャッシュドライバを使用する必要があります。さらに、すべてのサーバが同じ中央キャッシュサーバと通信している必要があります。[!WARNING]
To utilize this feature, your application must be using the memcached, redis, dynamodb, database, file, or array cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server.

ドライバ要件Driver Prerequisites

データベースDatabase

databaseキャッシュドライバを使用する場合は、アプリケーションのキャッシュロックを含むテーブルを設定する必要があります。以下にテーブルのSchema宣言の例を示します。When using the database cache driver, you will need to setup a table to contain your application's cache locks. You'll find an example Schema declaration for the table below:

Schema::create('cache_locks', function (Blueprint $table) {
    $table->string('key')->primary();
    $table->string('owner');
    $table->integer('expiration');
});

lightbulb Note: cache:table Artisanコマンドを使用し、データベースドライバのキャッシュテーブルを作成した場合、作成したマイグレーションには、あらかじめcache_locksテーブルの定義が含まれています。[!NOTE]
If you used the cache:table Artisan command to create the database driver's cache table, the migration created by that command already includes a definition for the cache_locks table.

ロック管理Managing Locks

アトミックロックを使用すると、競合状態を気にすることなく分散ロックを操作できます。たとえば、Laravel Forgeは、アトミックロックを使用して、サーバ上で一度に1つのリモートタスクのみが実行されるようにしています。Cache::lockメソッドを使用してロックを作成および管理できます。Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. For example, Laravel Forge[https://forge.laravel.com] uses atomic locks to ensure that only one remote task is being executed on a server at a time. You may create and manage locks using the Cache::lock method:

use Illuminate\Support\Facades\Cache;

$lock = Cache::lock('foo', 10);

if ($lock->get()) {
    // ロックを10秒間取得

    $lock->release();
}

getメソッドもクロージャを受け入れます。クロージャが実行された後、Laravelは自動的にロックを解除します。The get method also accepts a closure. After the closure is executed, Laravel will automatically release the lock:

Cache::lock('foo', 10)->get(function () {
    // ロックを10秒間取得し、自動的に開放
});

リクエストした時点でロックが利用できない場合に、指定された秒数待つようにLaravelへ指示できます。指定された制限時間内にロックを取得できない場合、Illuminate\Contracts\Cache\LockTimeoutExceptionを投げます。If the lock is not available at the moment you request it, you may instruct Laravel to wait for a specified number of seconds. If the lock can not be acquired within the specified time limit, an Illuminate\Contracts\Cache\LockTimeoutException will be thrown:

use Illuminate\Contracts\Cache\LockTimeoutException;

$lock = Cache::lock('foo', 10);

try {
    $lock->block(5);

    // ロック取得を最大5秒待つ
} catch (LockTimeoutException $e) {
    // ロック取得失敗
} finally {
    $lock?->release();
}

上記の例は、クロージャをblockメソッドに渡すことで簡略化できます。クロージャがこのメソッドに渡されると、Laravelは指定された秒数の間ロックを取得しようとし、クロージャが実行されると自動的にロックを解放します。The example above may be simplified by passing a closure to the block method. When a closure is passed to this method, Laravel will attempt to acquire the lock for the specified number of seconds and will automatically release the lock once the closure has been executed:

Cache::lock('foo', 10)->block(5, function () {
    // ロック取得を最大5秒待つ
});

プロセス間でのロック管理Managing Locks Across Processes

あるプロセスでロックを取得し、別のプロセスでそれを解放したい場合があります。たとえば、Webリクエスト中にロックを取得し、そのリクエストによってトリガーされたキュー投入済みジョブの終了時にロックを解放したい場合があるでしょう。このシナリオでは、ロックのスコープ付き「所​​有者トークン」をキュー投入済みジョブに渡し、ジョブが渡されたトークンを使用してロックを再インスタンス化できるようにする必要があります。Sometimes, you may wish to acquire a lock in one process and release it in another process. For example, you may acquire a lock during a web request and wish to release the lock at the end of a queued job that is triggered by that request. In this scenario, you should pass the lock's scoped "owner token" to the queued job so that the job can re-instantiate the lock using the given token.

以下の例では、ロックが正常に取得された場合に、キュー投入済みジョブをディスパッチします。さらに、ロックのownerメソッドを介して、ロックの所有者トークンをキュー投入済みジョブに渡します。In the example below, we will dispatch a queued job if a lock is successfully acquired. In addition, we will pass the lock's owner token to the queued job via the lock's owner method:

$podcast = Podcast::find($id);

$lock = Cache::lock('processing', 120);

if ($lock->get()) {
    ProcessPodcast::dispatch($podcast, $lock->owner());
}

アプリケーションのProcessPodcastジョブ内で、所有者トークンを使用してロックを復元し、解放できます。Within our application's ProcessPodcast job, we can restore and release the lock using the owner token:

Cache::restoreLock('processing', $this->owner)->release();

現在の所有者を尊重せずにロックを解放したい場合は、forceReleaseメソッドを使用できます。If you would like to release a lock without respecting its current owner, you may use the forceRelease method:

Cache::lock('processing')->forceRelease();

カスタムキャッシュドライバの追加Adding Custom Cache Drivers

ドライバの作成Writing the Driver

カスタムキャッシュドライバを作成するには、最初にIlluminate\Contracts\Cache\Store契約を実装する必要があります。したがって、MongoDBキャッシュの実装は次のようになります。To create our custom cache driver, we first need to implement the Illuminate\Contracts\Cache\Store contract[/docs/{{version}}/contracts]. So, a MongoDB cache implementation might look something like this:

<?php

namespace App\Extensions;

use Illuminate\Contracts\Cache\Store;

class MongoStore implements Store
{
    public function get($key) {}
    public function many(array $keys) {}
    public function put($key, $value, $seconds) {}
    public function putMany(array $values, $seconds) {}
    public function increment($key, $value = 1) {}
    public function decrement($key, $value = 1) {}
    public function forever($key, $value) {}
    public function forget($key) {}
    public function flush() {}
    public function getPrefix() {}
}

MongoDB接続を使用してこれらの各メソッドを実装する必要があります。これらの各メソッドを実装する方法の例については、LaravelフレームワークのソースコードIlluminate\Cache\MemcachedStoreをご覧ください。実装が完了したら、Cacheファサードのextendメソッドを呼び出してカスタムドライバの登録を完了してください。We just need to implement each of these methods using a MongoDB connection. For an example of how to implement each of these methods, take a look at the Illuminate\Cache\MemcachedStore in the Laravel framework source code[https://github.com/laravel/framework]. Once our implementation is complete, we can finish our custom driver registration by calling the Cache facade's extend method:

Cache::extend('mongo', function (Application $app) {
    return Cache::repository(new MongoStore);
});

lightbulb Note: カスタムキャッシュドライバコードをどこに置くか迷っている場合は、appディレクトリ内にExtensions名前空間を作成できます。ただし、Laravelには厳密なアプリケーション構造がなく、好みに応じてアプリケーションを自由にオーガナイズできることに注意してください。[!NOTE]
If you're wondering where to put your custom cache driver code, you could create an Extensions namespace within your app directory. However, keep in mind that Laravel does not have a rigid application structure and you are free to organize your application according to your preferences.

Registering the DriverRegistering the Driver

カスタムキャッシュドライバをLaravelに登録するには、Cacheファサードでextendメソッドを使用します。他のサービスプロバイダはbootメソッド内でキャッシュされた値を読み取ろうとする可能性があるため、bootingコールバック内にカスタムドライバを登録します。bootingコールバックを使用することで、アプリケーションのサービスプロバイダでbootメソッドが呼び出される直前で、すべてのサービスプロバイダでregisterメソッドが呼び出された後にカスタムドライバが登録されるようにすることができます。アプリケーションのApp\Providers\AppServiceProviderクラスのregisterメソッド内にbootingコールバックを登録します。To register the custom cache driver with Laravel, we will use the extend method on the Cache facade. Since other service providers may attempt to read cached values within their boot method, we will register our custom driver within a booting callback. By using the booting callback, we can ensure that the custom driver is registered just before the boot method is called on our application's service providers but after the register method is called on all of the service providers. We will register our booting callback within the register method of our application's App\Providers\AppServiceProvider class:

<?php

namespace App\Providers;

use App\Extensions\MongoStore;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションの全サービスの登録
     */
    public function register(): void
    {
        $this->app->booting(function () {
             Cache::extend('mongo', function (Application $app) {
                 return Cache::repository(new MongoStore);
             });
         });
    }

    /**
     * 全アプリケーションサービスの初期起動処理
     */
    public function boot(): void
    {
        // ...
    }
}

extendメソッドに渡す最初の引数はドライバの名前です。これは、config/cache.php設定ファイルのdriverオプションに対応させます。2番目の引数は、Illuminate\Cache\Repositoryインスタンスを返す必要があるクロージャです。クロージャには、サービスコンテナのインスタンスである$appインスタンスが渡されます。The first argument passed to the extend method is the name of the driver. This will correspond to your driver option in the config/cache.php configuration file. The second argument is a closure that should return an Illuminate\Cache\Repository instance. The closure will be passed an $app instance, which is an instance of the service container[/docs/{{version}}/container].

拡張機能を登録したら、config/cache.php設定ファイルのdriverオプションを拡張機能の名前に更新します。Once your extension is registered, update your config/cache.php configuration file's driver option to the name of your extension.

イベントEvents

キャッシュ操作のどこででもコードを実行するには、キャッシュが発生させるイベントをリッスンしてください。通常、これらのイベントリスナはアプリケーションのApp\Providers\EventServiceProviderクラス内に配置する必要があります。To execute code on every cache operation, you may listen for the events[/docs/{{version}}/events] fired by the cache. Typically, you should place these event listeners within your application's App\Providers\EventServiceProvider class:

use App\Listeners\LogCacheHit;
use App\Listeners\LogCacheMissed;
use App\Listeners\LogKeyForgotten;
use App\Listeners\LogKeyWritten;
use Illuminate\Cache\Events\CacheHit;
use Illuminate\Cache\Events\CacheMissed;
use Illuminate\Cache\Events\KeyForgotten;
use Illuminate\Cache\Events\KeyWritten;

/**
 * アプリケーションのイベントリスナマップ
 *
 * @var array
 */
protected $listen = [
    CacheHit::class => [
        LogCacheHit::class,
    ],

    CacheMissed::class => [
        LogCacheMissed::class,
    ],

    KeyForgotten::class => [
        LogKeyForgotten::class,
    ],

    KeyWritten::class => [
        LogKeyWritten::class,
    ],
];

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作