Readouble

Laravel 5.1 キャシュ

設定Configuration

Laravelは多くのキャッシュシステムに統一したAPIを提供します。キャッシュの設定はconfig/cache.phpで設定します。アプリケーション全体でデフォルトとして使用するキャッシュドライバーをこのファイルの中で指定します。MemcachedRedisなど、人気のあるキャッシュシステムをLaravelは最初からサポートしています。Laravel provides a unified API for various caching systems. 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 an in-memory cache such as Memcached or APC. You may even configure multiple cache configurations for the same driver.

キャッシュ動作要件Cache 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');
});

MemcachedMemcached

Memcachedキャッシュを使用する場合はMemcached PECLパッケージをインストールする必要があります。Using the Memcached cache requires the Memcached PECL package[http://pecl.php.net/package/memcached] to be installed.

デフォルト設定ではTCP/IPベースのMemcached::addServerを使用します。The default configuration[#configuration] uses TCP/IP based on Memcached::addServer[http://php.net/manual/en/memcached.addserver.php]:

'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].

キャッシュの使用法Cache 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.

例としてコントローラーでCacheファサードを使ってみましょう。For example, let's import the Cache facade into a controller:

<?php

namespace App\Http\Controllers;

use Cache;
use Illuminate\Routing\Controller;

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 custom 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 optionally accept a 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 Or Update

キャッシュからアイテムを取得しようとして、指定したアイテムが存在しない場合はデフォルト値を保存したいことも時にはあるでしょう。たとえば全ユーザーをキャッシュから取得しようとし、存在していない場合はデータベースから取得しキャシュへ追加したい場合です。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.

rememberforeverメソッドを一緒に行うこともできます。You may also combine the remember and forever methods:

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

取得後削除Retrieve And Delete

キャッシュからアイテムを取得した後に削除したい場合は、pullメソッドを使用します。getメソッドと同様にキャッシュにアイテムが存在していない場合は、nullが返ります。If you need to retrieve an item from the cache and then delete it, 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 will need to specify the number of minutes for which the value should be cached:

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

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

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

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

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);

foreverメソッドはそのアイテムをキャッシュへ永遠に保存します。こうした値はforgetメソッドを使用し、手動で削除する必要があります。The forever method may be used to store an item in the cache permanently. These values must be manually removed from the cache using the forget method:

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

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

Cacheファサードのforgetメソッドでキャッシュからアイテムを削除します。You may remove items from the cache using the forget method on the Cache facade:

Cache::forget('key');

You may clear the entire cache using the flush method:You may clear the entire cache using the flush method:

Cache::flush();

flushメソッドはキャッシュのプレフィックスを考慮せずに、キャッシュから全アイテムを削除します。他のアプリケーションと共有するキャッシュを削除するときに、利用を考慮してください。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.

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

Laravelキャッシュをカスタムドライバーで拡張するには、マネージャーにカスタムドライバーリゾルバ―を結合するために使用するCacheファサードのextendメソッドを使います。通常これはサービスプロバイダーの中で行います。To extend the Laravel cache with a custom driver, we will use the extend method on the Cache facade, which is used to bind a custom driver resolver to the manager. Typically, this is done within a service provider[/docs/{{version}}/providers].

例として"mongo"という名前のキャッシュドライバーを登録してみましょう。For example, to register a new cache driver named "mongo":

<?php

namespace App\Providers;

use Cache;
use App\Extensions\MongoStore;
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].

Cache::extendはインストールしたてのLaravelアプリケーションに含まれているデフォルトのApp\Providers\AppServiceProviderbootメソッドで呼び出すか、もしくは拡張のためにサービスプロバイダーを新たに作成することもできるでしょう。この場合はサービスプロバイダーをconfig/app.phpのproviders配列へ登録するのを忘れないでください。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.

カスタムキャッシュドライバーを作成するには、最初に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, our MongoDB cache implementation would look something like this:

<?php

namespace App\Extensions;

class MongoStore implements \Illuminate\Contracts\Cache\Store
{
    public function get($key) {}
    public function put($key, $value, $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接続を使い各メソッドを実装する必要があります。実装が完成したらカスタムドライバー登録を完了させましょう。We just need to implement each of these methods using a MongoDB connection. Once our implementation is complete, we can finish our custom driver registration:

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

拡張が完了したら、config/cache.php設定ファイルのdriverオプションを作成した拡張名に更新してください。Once your extension is complete, simply update your config/cache.php configuration file's driver option to the name of your extension.

カスタムキャッシュドライバーコードをどこに設置するか迷っているのであれば、Packagistで公開することを考えてください! もしくはappディレクトリーにExtensions名前空間を作成することもできます。しかしLaravelは厳格なアプリケーション構造を持たないため、自分の好みに応じてアプリケーションを系統立てられることを忘れないでください。If you're wondering where to put your custom cache driver code, consider making it available on Packagist! Or, 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.

キャッシュタグCache Tags

注意: キャッシュタグは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 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);

しかし、putメソッドだけに限りません。キャッシュの保存メソッドは全部タグで操作できます。However, you are not limited to the put method. You may use any cache storage method while working with tags.

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

タグ付けしたキャッシュアイテムを取得するには、tagsメソッドに同じ順序でタグのリストを渡してください。To retrieve a tagged cache item, pass the same ordered list of tags to the tags method:

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

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

タグ一つ、もしくはタグのリストに結びついた全アイテムを一度に消去することができます。例えば、次の実行文は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();

キャッシュイベントCache Events

キャッシュ操作が起きるごとにコードを実行するには、キャッシュにより発行されるイベントをリッスンしてください。通常、EventServiceProviderbootメソッドの中にイベントハンドラーを設置することになるでしょう。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 the boot method of your EventServiceProvider:

/**
 * アプリケーションのその他のイベントの登録
 *
 * @param  \Illuminate\Contracts\Events\Dispatcher  $events
 * @return void
 */
public function boot(DispatcherContract $events)
{
    parent::boot($events);

    $events->listen('cache.hit', function ($key, $value) {
        //
    });

    $events->listen('cache.missed', function ($key) {
        //
    });

    $events->listen('cache.write', function ($key, $value, $minutes) {
        //
    });

    $events->listen('cache.delete', function ($key) {
        //
    });
}

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作