Readouble

Laravel master キャシュ

設定Configuration

Laravelは多くのキャッシュシステムに読み書きしやすい、統一したAPIを提供します。キャッシュの設定はconfig/cache.phpで設定します。アプリケーション全体でデフォルトとして使用するキャッシュドライバをこのファイルの中で指定します。MemcachedRedisなど、人気のあるキャッシュシステムをLaravelは最初からサポートしています。Laravel provides an expressive, unified API for various caching backends. The cache configuration is located at config/cache.php. In this file you may specify which cache driver you would like used by default throughout your application. Laravel supports popular caching backends like Memcached[http://memcached.org] and Redis[http://redis.io] out of the box.

キャッシュ設定ファイルは、様々な他のオプションも含んでいます。コメントで説明してありますので、よく読んで確認してください。Laravelのデフォルトとして、fileキャッシュドライバが設定されています。ファイルシステムへオブジェクトをシリアライズして保存します。大きなアプリケーションではMemecachedやAPCのような、より堅牢なドライバを使うことをおすすめします。複数のドライバを使用するキャッシュ設定も可能です。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 in the 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

データベースをキャッシュドライバに使用する場合、キャッシュアイテムを構成するテーブルを用意する必要があります。このテーブルの「スキーマ」を定義するサンプルを見てください。When using the database cache driver, you will need to setup a table to contain the cache items. You'll find an example Schema declaration for the table below:

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

lightbulb">Tip!! 正確なスキマーのマイグレーションを生成するために、php artisan cache:table Artisanコマンドを使用することもできます。{tip} 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設定ファイルにリストしてください。Using the Memcached driver requires the Memcached PECL package[http://pecl.php.net/package/memcached] to be installed. You may list all of your Memcached servers in the config/cache.php configuration file:

'memcached' => [
    [
        'host' => '127.0.0.1',
        'port' => 11211,
        'weight' => 100
    ],
],

さらに、UNIXソケットパスへ、hostオプションを設定することもできます。これを行うにはportオプションに0を指定してください。You may also 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キャシュを使用する場合、predis/predisパッケージ(~1.0)をComposerでインストールする必要があります。Before using a Redis cache with Laravel, you will need to install the predis/predis package (~1.0) via Composer.

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

キャシュ UsageCache Usage

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

Illuminate\Contracts\Cache\FactoryIlluminate\Contracts\Cache\Repository契約は、Laravelのキャッシュサービスへのアクセスを提供します。Factory契約は、アプリケーションで定義している全キャッシュドライバへのアクセスを提供します。Repository契約は通常、cache設定ファイルで指定している、アプリケーションのデフォルトキャッシュドライバの実装です。The Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository contracts[/docs/{{version}}/contracts] provide access to Laravel's cache services. The Factory contract provides access to all cache drivers defined for your application. The Repository contract is typically an implementation of the default cache driver for your application as specified by your cache configuration file.

しかし、このドキュメント全体で使用している、Cacheファサードも利用できます。Cacheファサードは裏で動作している、Laravelキャッシュ契約の実装への便利で簡潔なアクセスを提供しています。However, you may also 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
{
    /**
     * アプリケーションの全ユーザリストの表示
     *
     * @return Response
     */
    public function index()
    {
        $value = Cache::get('key');

        //
    }
}

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

Cacheファサードのstoreメソッドを使い、様々なキャッシュ保存域へアクセスできます。storeメソッドに渡すキーは、cache設定ファイルのstores設定配列にリストしている保存域の一つです。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', 10);

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

Cacheファサードのgetメソッドは、キャッシュからアイテムを取得するために使用します。アイテムがキャッシュに存在していない場合は、nullが返されます。アイテムが存在していない時に返したい、カスタムデフォルト値をgetメソッドの第2引数として渡すこともできます。The get method on the Cache facade 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();
});

アイテムの存在確認Checking For Item Existence

hasメソッドでキャッシュにアイテムが存在しているかを調べることができます。The has method may be used to determine if an item exists in the cache:

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

値の増減Incrementing / Decrementing Values

incrementdecrementメソッドはキャッシュの整数アイテムの値を調整するために使用します。両方のメソッドともそのアイテムの値をどのくらい増減させるかの増分をオプションの第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::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);

取得不可時更新Retrieve & 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', $minutes, 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.

取得後削除Retrieve & 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. When you place an item in the cache, you need to specify the number of minutes for which the value should be cached:

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

どのくらいでアイテムが無効になるかを分数で指定する代わりに、キャッシュされたアイテムの有効期限を示すDateTimeインスタンスを渡すこともできます。Instead of passing the number of minutes as an integer, you may also pass a DateTime instance representing the expiration time of the cached item:

$expiresAt = Carbon::now()->addMinutes(10);

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

非存在時保存Store If Not Present

addメソッドはキャッシュに保存されていない場合のみ、そのアイテムを保存します。キャッシュに実際にアイテムが追加された場合はtrueが返ってきます。そうでなければfalseが返されます。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:

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

アイテムを永遠に保存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">Tip!! Memcachedドライバーを使用する場合、キャッシュが最大値に達すると、"forever"を指定したアイテムも削除されます。{tip} 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');

キャッシュ全体をクリアしたい場合はflushメソッドを使います。You may clear the entire cache using the flush method:

Cache::flush();

Note: note flushメソッドは、キャッシュのプレフィックスを考慮せずに、キャッシュから全アイテムを削除します。他のアプリケーションと共有するキャッシュを削除するときは、利用を熟考してください。{note} Flushing the cache does not respect the cache prefix and will remove all entries from the cache. Consider this carefully when clearing a cache which is shared by other applications.

cacheヘルパThe Cache Helper

CacheファサードとCache契約に付け加え、キャッシュからのデータ取得/保存を行う、グローバルcache関数も使用できます。cache関数を文字列引数一つで呼び出す場合、指定したキーの値を返します。In addition to using the Cache facade or cache contract[/docs/{{version}}/contracts], 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'], $minutes);

cache(['key' => 'value'], Carbon::now()->addSeconds(10));

グローバルcache関数への呼び出しをテストする場合、ファサードのテストと同様に、Cache::shouldReceiveメソッドを使います。{tip} When testing call to the global cache function, you may use the Cache::shouldReceive method just as if you were testing a facade[/docs/{{version}}/mocking#mocking-facades].

キャシュ TagsCache Tags

Note: note filedatabaseキャッシュドライバ使用時、キャッシュタグはサポートされません。また、"forever"を使い、複数のタグをつけたキャッシュを使用する場合、古いレコードを自動的にパージするmemcachedのようなドライバがパフォーマンス的に最適です。{note} Cache tags are not supported when using the file or database cache drivers. Furthermore, when using multiple tags with caches that are stored "forever", performance will be best with a driver such as memcached, which automatically purges stale records.

タグ付けキャッシュアイテムの保存Storing Tagged Cache Items

キャシュタグにより、キャッシュ中の関連するアイテムへタグ付けできます。その後、指定したタグがつけられたキャッシュの値を全部削除できます。タグを順番に指定する配列を渡すことで、タグ付けしたキャッシュへアクセスできます。例としてタグ付けしたキャッシュにアクセスし、キャッシュへ値をputしてみましょう。Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered array of tag names. For example, let's access a tagged cache and put value in the cache:

Cache::tags(['people', 'artists'])->put('John', $john, $minutes);

Cache::tags(['people', 'authors'])->put('Anne', $anne, $minutes);

タグ付けキャッシュアイテムへのアクセスAccessing Tagged Cache Items

タグ付けしたキャッシュアイテムを取得するには、tagsメソッドに同じ順序でタグのリストを渡し、続けてgetメソッドで取得したいキーを指定します。。To retrieve a tagged cache item, pass the same ordered list of tags to the tags method and then call the get method with the key you wish to retrieve:

$john = Cache::tags(['people', 'artists'])->get('John');

$anne = Cache::tags(['people', 'authors'])->get('Anne');

タグ付けキャッシュアイテムの削除Removing Tagged Cache Items

タグ一つ、もしくはタグのリストに結びついた全アイテムを一度に消去することができます。たとえば、次の実行文はpeopleauthorsのどちらか、または両方にタグ付けされたキャッシュを全部削除します。ですから、AnneJohnは両方共キャッシュから削除されます。You may flush all items that are assigned a tag or list of tags. For example, this statement would remove all caches tagged with either people, authors, or both. So, both Anne and John would be removed from the cache:

Cache::tags(['people', 'authors'])->flush();

対照的に、次の実行分ではauthorsにタグ付けしたキャッシュのみ削除されますので、Anneが削除され、Johnは残ります。In contrast, this statement would remove only caches tagged with authors, so Anne would be removed, but not John:

Cache::tags('authors')->flush();

カスタムキャッシュドライバの追加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] contract. So, a MongoDB cache implementation would 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, $minutes) {}
    public function putMany(array $values, $minutes);
    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接続を用い、実装するだけです。各メソッドをどのように実装するかの例は、フレームワークのIlluminate\Cache\MemcachedStoreのソースコードを参照してください。実装を完了したら、ドライバを登録します。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 framework source code. Once our implementation is complete, we can finish our custom driver registration.

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

lightbulb">Tip!! カスタムキャッシュドライバーをどこに設置するか迷っているなら、appディレクトリ下にExtensionsの名前空間で作成できます。しかし、Laravelはアプリケーション構造を強制していませんので、自分の好みに合わせてアプリケーションを自由に構築できることを忘れないでください。{tip} 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 Driver

Laravelにカスタムキャッシュドライバを登録するには、Cacheファサードのextendメソッドを使います。新しくインストールしたLaravelに含まれている、デフォルトのApp\Providers\AppServiceProviderbootメソッドで、Cache::extendを呼び出せます。もしくは、拡張を設置するために自身のサービスプロバイダを作成することもできます。config/app.phpプロバイダ配列に、そのプロバイダを登録し忘れないようにしてください。To register the custom cache driver with Laravel, we will use the extend method on the Cache facade. The call to Cache::extend could be done in the boot method of the default App\Providers\AppServiceProvider that ships with fresh Laravel applications, or you may create your own service provider to house the extension - just don't forget to register the provider in the config/app.php provider array:

<?php

namespace App\Providers;

use App\Extensions\MongoStore;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;

class CacheServiceProvider extends ServiceProvider
{
    /**
     * サービス起動後の登録処理
     *
     * @return void
     */
    public function boot()
    {
        Cache::extend('mongo', function($app) {
            return Cache::repository(new MongoStore);
        });
    }

    /**
     * コンテナへ結合を登録
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

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, simply update your config/cache.php configuration file's driver option to the name of your extension.

イベントEvents

全キャッシュ操作に対してコードを実行するには、キャッシュが発行するイベントを購読する必要があります。通常、イベントリスナは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 EventServiceProvider:

/**
 * アプリケーションのイベントリスナ
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Cache\Events\CacheHit' => [
        'App\Listeners\LogCacheHit',
    ],

    'Illuminate\Cache\Events\CacheMissed' => [
        'App\Listeners\LogCacheMissed',
    ],

    'Illuminate\Cache\Events\KeyForgotten' => [
        'App\Listeners\LogKeyForgotten',
    ],

    'Illuminate\Cache\Events\KeyWritten' => [
        'App\Listeners\LogKeyWritten',
    ],
];

章選択

開発環境
ビューとテンプレート
公式パッケージ

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作