Readouble

Laravel 5.1 セッション

イントロダクションIntroduction

HTTP駆動のアプリケーションはステートレスですから、リクエスト間に渡り情報を保存するセッションが提供されています。Laravelは美しく統一されたAPIを使える様々なバックエンドのセッションを用意しています。人気のあるMemcachedRedis、データベースも始めからサポートしています。Since HTTP driven applications are stateless, sessions provide a way to store information about the user across requests. Laravel ships with a variety of session back-ends available for use through a clean, unified API. Support for popular back-ends such as Memcached[http://memcached.org], Redis[http://redis.io], and databases is included out of the box.

設定Configuration

セッションの設定はconfig/session.phpにあります。このファイルのオプションには詳しくコメントがついていますので確認して下さい。ほとんどのアプリケーションでうまく動作できるように、Laravelはfileセッションドライバーをデフォルトとして設定しています。実働環境のアプリケーションではセッションの動作をより早くするために、memcachedredisドライバーの使用を考慮しましょう。The session configuration file is stored at config/session.php. Be sure to review the well documented options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for many applications. In production applications, you may consider using the memcached or redis drivers for even faster session performance.

セッションドライバー(driver)はリクエスト毎のセッションデータをどこに保存するかを決めます。Laravelには最初から素晴らしいドライバーが用意されています。The session driver defines where session data will be stored for each request. Laravel ships with several great drivers out of the box:

- `file` - セッションは`storage/framework/sessions`に保存されます。 - `cookie` - セションは暗号化され安全なクッキーに保存されます。 - `database` - セッションはアプリケーションで使用しているデータベースに保存されます。 - `memcached`/`redis` - セッションはスピードの早いキャッシュベースの保存域に保存されます。 - `array` - セッションは単にPHPの配列として保存されるだけで、リクエスト間で継続しません。

注意: セッションデータが持続しないように、arrayドライバーは通常テストの実行で使用されます。Note: The array driver is typically used for running tests[/docs/{{version}}/testing] to prevent session data from persisting.

ドライバーの事前要件Driver Prerequisites

データベースDatabase

databaseセッションドライバーを使う場合、セッションアイテムを含むテーブルを準備する必要があります。以下にこのテーブル宣言のサンプル「スキーマ」を示します。When using the database session driver, you will need to setup a table to contain the session items. Below is an example Schema declaration for the table:

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->text('payload');
    $table->integer('last_activity');
});

session:table Artisanコマンドを使えば、このマイグレーションが生成できます!You may use the session:table Artisan command to generate this migration for you!

php artisan session:table

composer dump-autoload

php artisan migrate

RedisRedis

ReidsセッションをLaravelで使用する前に、Composerでpredis/predisパッケージ(~1.0)をインストールする必要があります。Before using Redis sessions with Laravel, you will need to install the predis/predis package (~1.0) via Composer.

その他セッションでの考慮点Other Session Considerations

Laravelフレームワークはflashセッションキーを内部で使用しているため、この名前でアイテムをセッションに追加してはいけません。The Laravel framework uses the flash session key internally, so you should not add an item to the session by that name.

セッションに保存する全データを暗号化したい場合、encrypt設定オプションをtrueに指定してください。If you need all stored session data to be encrypted, set the encrypt configuration option to true.

基本的な使用法Basic Usage

セッションへのアクセスAccessing The Session

最初にセッションへアクセスしてみましょう。コントローラーメソッドでタイプヒントを指定し、HTTPリクエストを経由してセッションをインスタンスへアクセスできます。コントローラーメソッドの依存はLaravelのサービスコンテナにより注入されることを覚えておきましょう。First, let's access the session. We can access the session instance via the HTTP request, which can be type-hinted on a controller method. Remember, controller method dependencies are injected via the Laravel service container[/docs/{{version}}/container]:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 指定ユーザーのプロフィールを表示
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function showProfile(Request $request, $id)
    {
        $value = $request->session()->get('key');

        //
    }
}

セッションから値を取得するときに、getメソッドの第2引数としてデフォルト値を渡せます。このデフォルト値は指定したキーがセッションに存在していない場合に返されます。デフォルト値として「クロージャー」をgetメソッドへ渡す場合、その「クロージャー」の実行結果が返されます。When you retrieve a value from the session, you may also pass a default value as the second argument to the get method. This default value will be returned if the specified key does not exist in the session. If you pass a Closure as the default value to the get method, the Closure will be executed and its result returned:

$value = $request->session()->get('key', 'default');

$value = $request->session()->get('key', function() {
    return 'default';
});

セッションから全データを取得したい場合は、allメソッドを使用してください。If you would like to retrieve all data from the session, you may use the all method:

$data = $request->session()->all();

セッションから取得したり、保存したりするためにグローバルのsessionヘルパ関数を使用することができます。You may also use the global session PHP function to retrieve and store data in the session:

Route::get('home', function () {
    // セッションからデータを一つ取得…
    $value = session('key');

    // セッションへデータ一つを保存…
    session(['key' => 'value']);
});

セッション中のアイテム存在を確認Determining If An Item Exists In The Session

hasメソッドでセッションにアイテムが存在するかを調べられます。このメソッドは存在している場合にtrueを返します。The has method may be used to check if an item exists in the session. This method will return true if the item exists:

if ($request->session()->has('users')) {
    //
}

セッションへのデータ保存Storing Data In The Session

セッションインスタンスへアクセスしたら、データを操作するために数々のメソッドを呼び出せます。たとえば新しいデータをセッションへ保存するにはputを使います。Once you have access to the session instance, you may call a variety of functions to interact with the underlying data. For example, the put method stores a new piece of data in the session:

$request->session()->put('key', 'value');

配列セッション値の追加Pushing To Array Session Values

pushメソッドは新しい値を配列のセッション値へ追加します。たとえばuser.teamsキーにチーム名の配列が含まれているなら、新しい値を次のように追加できます。The push method may be used to push a new value onto a session value that is an array. For example, if the user.teams key contains an array of team names, you may push a new value onto the array like so:

$request->session()->push('user.teams', 'developers');

取得後アイテムを削除Retrieving And Deleting An Item

pullメソッドでセッションからアイテムを取得後、削除できます。The pull method will retrieve and delete an item from the session:

$value = $request->session()->pull('key', 'default');

セッションからアイテムを削除Deleting Items From The Session

forgetメソッドでセッションからデータを削除できます。セッションから全データを削除したければ、flushメソッドが使用できます。The forget method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the flush method:

$request->session()->forget('key');

$request->session()->flush();

セッションIDの再生成Regenerating The Session ID

セッションIDを再生成する必要がある場合、regenerateメソッドを使ってください。If you need to regenerate the session ID, you may use the regenerate method:

$request->session()->regenerate();

フラッシュデータFlash Data

次のリクエスト間だけセッションにアイテムを保存したいことは良くあります。flashメソッドを使ってください。flashメソッドは直後のHTTPリクエストの間だけセッションにデータを保存します。それ以降は削除されます。フラッシュデータは主にステータスメッセージなど継続しない情報に便利です。Sometimes you may wish to store items in the session only for the next request. You may do so using the flash method. Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted. Flash data is primarily useful for short-lived status messages:

$request->session()->flash('status', 'タスクは成功しました!');

フラッシュデータをさらにその先のリクエストまで持続させたい場合は、reflashメソッドを使い全フラッシュデータをその先のリクエストまで持続させられます。特定のフラッシュデータのみ持続させたい場合は、keepメソッドを使います。If you need to keep your flash data around for even more requests, you may use the reflash method, which will keep all of the flash data around for an additional request. If you only need to keep specific flash data around, you may use the keep method:

$request->session()->reflash();

$request->session()->keep(['username', 'email']);

カスタムセッションドライバーの追加Adding Custom Session Drivers

Laravelのセッションのバックエンドにドライバーを追加したい場合、Sessionファサードextendメソッドを使用します。サービスプロバイダーbootメソッドからextendメソッドを呼び出してください。To add additional drivers to Laravel's session back-end, you may use the extend method on the Session facade[/docs/{{version}}/facades]. You can call the extend method from the boot method of a service provider[/docs/{{version}}/providers]:

<?php

namespace App\Providers;

use Session;
use App\Extensions\MongoSessionStore;
use Illuminate\Support\ServiceProvider;

class SessionServiceProvider extends ServiceProvider
{
    /**
     * サービスの初期処理登録後に実行
     *
     * @return void
     */
    public function boot()
    {
        Session::extend('mongo', function($app) {
            // SessionHandlerInterfaceの実装を返す…
            return new MongoSessionStore;
        });
    }

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

カスタムセッションドライバーはSessionHandlerInterfaceを実装している点に注意してください。このインターフェイスは実装が必要なシンプルなメソッドで構成されています。MongoDBのスタブ実装は次のようになるでしょう。Note that your custom session driver should implement the SessionHandlerInterface. This interface contains just a few simple methods we need to implement. A stubbed MongoDB implementation looks something like this:

<?php

namespace App\Extensions;

class MongoHandler implements SessionHandlerInterface
{
    public function open($savePath, $sessionName) {}
    public function close() {}
    public function read($sessionId) {}
    public function write($sessionId, $data) {}
    public function destroy($sessionId) {}
    public function gc($lifetime) {}
}

キャッシュの「保存インターフェイス」として、これらのメソッドは理解しづらいでしょうから簡単に各メソッドを説明します。Since these methods are not as readily understandable as the cache StoreInterface, let's quickly cover what each of the methods do:

- `open`メソッドは通常ファイルベースのセッション保存システムで使われます。Laravelは`file`セッションドライバーを用意していますが、皆さんはこのメソッドに何も入れる必要はないでしょう。空のスタブのままで良いでしょう。実際、PHPが実装するように要求しているこのメソッドは、下手なインターフェイスデザインなのです。 - `close`メソッドも`open`と同様に通常は無視できます。ほどんどのドライバーでは必要ありません。 - `read`メソッドは指定された`$sessionId`と紐付いたセッションデータの文字列バージョンを返します。取得や保存時にドライバー中でデータをシリアライズしたり、他のエンコード作業を行ったりする必要はありません。Laravelがシリアライズを行います。 - `write`メソッドはMongoDBやDynamoなどの持続可能なストレージに、`$sessionId`に紐付け指定した`$data`文字列を書き出します。 - `destroy`メソッドは持続可能なストレージから`$sessionId`に紐付いたデータを取り除きます。 - `gc`メソッドは指定したUNIXタイムスタンプの`$lifetime`よりも古い前セッションデータを削除します。自前で破棄するMemcachedやRedisのようなシステムでは、このメソッドは空のままにしておきます。

セッションドライバーを登録したら、config/session.php設定ファイルでmongoドライバーが使用できます。Once the session driver has been registered, you may use the mongo driver in your config/session.php configuration file.

章選択

設定

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

ヘッダー項目移動

キーボード操作