Readouble

Laravel master イベント

イントロダクションIntroduction

Laravelのイベントはシンプルなオブザーバの実装で、アプリケーションで発生する様々なイベントを購読し、リッスンするために使用します。イベントクラスは通常、app/Eventsディレクトリに保存されます。一方、リスナはapp/Listenersディレクトリへ保存されます。アプリケーションに両ディレクトリが存在しなくても、心配ありません。Artisanコンソールコマンドを使い、イベントとリスナを生成するとき、ディレクトリも生成されます。Laravel's events provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. Don't worry if you don't see these directories in your application, since they will be created for you as you generate events and listeners using Artisan console commands.

一つのイベントは、互いに依存していない複数のリスナに紐付けられますので、アプリケーションの様々な側面を独立させるための良い手段として、イベントを利用できます。たとえば、注文を配送するごとにSlack通知をユーザへ届けたいとします。注文の処理コードとSlackの通知コードを結合する代わりに、シンプルにOrderShippedイベントを発行し、リスナがそれを受け取り、Slack通知へ変換するように実装できます。Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can simply raise an OrderShipped event, which a listener can receive and transform into a Slack notification.

イベント/リスナ登録Registering Events & Listeners

Laravelアプリケーションに含まれているEventServiceProviderは、イベントリスナを全て登録するために便利な場所を提供しています。listenプロパティは全イベント(キー)とリスナ(値)で構成されている配列です。もちろん、アプリケーションで必要とされているイベントをこの配列に好きなだけ追加できます。たとえばOrderShippedイベントを追加してみましょう。The EventServiceProvider included with your Laravel application provides a convenient place to register all of your application's event listeners. The listen property contains an array of all events (keys) and their listeners (values). Of course, you may add as many events to this array as your application requires. For example, let's add a OrderShipped event:

/**
 * アプリケーションのイベントリスナをマップ
 *
 * @var array
 */
protected $listen = [
    'App\Events\OrderShipped' => [
        'App\Listeners\SendShipmentNotification',
    ],
];

イベント/リスナ生成Generating Events & Listeners

毎回ハンドラやリスナを作成するのは、当然のことながら手間がかかります。代わりにハンドラとリスナをEventServiceProviderに追加し、event:generateコマンドを使いましょう。このコマンドはEventServiceProviderにリストしてあるイベントやリスナを生成してくれます。既存のイベントとハンドラには、もちろん変更を加えません。Of course, manually creating the files for each event and listener is cumbersome. Instead, simply add listeners and events to your EventServiceProvider and use the event:generate command. This command will generate any events or listeners that are listed in your EventServiceProvider. Of course, events and listeners that already exist will be left untouched:

php artisan event:generate

イベントの手動登録Manually Registering Events

通常イベントは、EventServiceProvider$listen配列により登録するべきです。しかし、EventServiceProviderbootメソッドの中で、クロージャベースリスナを登録することができます。Typically, events should be registered via the EventServiceProvider $listen array; however, you may also register Closure based events manually in the boot method of your EventServiceProvider:

/**
 * アプリケーションの他のイベントを登録する
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    Event::listen('event.name', function ($foo, $bar) {
        //
    });
}

ワイルドカードリスナWildcard Event Listeners

登録したリスナが、*をワイルドカードパラメータとしてシヨウシテイル場合、同じリスナで複数のイベントを捕捉できます。ワイルドカードリスナは、イベント全体のデータ配列を最初の引数で受け取ります。You may even register listeners using the * as a wildcard parameter, allowing you to catch multiple events on the same listener. Wildcard listeners receive the entire event data array as a single argument:

Event::listen('event.*', function (array $data) {
    //
});

イベント定義Defining Events

イベントクラスはシンプルなデータコンテナで、イベントに関する情報を保持します。たとえば生成したOrderShippedイベントがEloquent ORMオブジェクトを受け取るとしましょう。An event class is simply a data container which holds the information related to the event. For example, let's assume our generated OrderShipped event receives an Eloquent ORM[/docs/{{version}}/eloquent] object:

<?php

namespace App\Events;

use App\Order;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;

class OrderShipped extends Event
{
    use SerializesModels;

    public $order;

    /**
     * 新しいイベントインスタンスの生成
     *
     * @param  Order  $order
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }
}

ご覧の通り、このクラスはロジックを含みません。購入されたOrderオブジェクトのための、単なるコンテナに過ぎません。イベントオブジェクトがPHPのserialize関数でシリアライズされる場合でも、EloquentモデルをイベントがuseしているSerializesModelsトレイトが優雅にシリアライズします。As you can see, this event class contains no logic. It is simply a container for the Order instance that was purchased. The SerializesModels trait used by the event will gracefully serialize any Eloquent models if the event object is serialized using PHP's serialize function.

リスナの定義Defining Listeners

次にサンプルイベントのリスナを取り上げましょう。イベントリスナはイベントインスタンスをhandleメソッドで受け取ります。event:generateコマンドは自動的に適切なイベントクラスをインポートし、handleメソッドのイベントのタイプヒントを指定します。そのイベントに対応するために必要なロジックをhandleメソッドで実行してください。Next, let's take a look at the listener for our example event. Event listeners receive the event instance in their handle method. The event:generate command will automatically import the proper event class and type-hint the event on the handle method. Within the handle method, you may perform any actions necessary to respond to the event:

<?php

namespace App\Listeners;

use App\Events\OrderShipped;

class SendShipmentNotification
{
    /**
     * イベントリスナ生成
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * イベントの処理
     *
     * @param  OrderShipped  $event
     * @return void
     */
    public function handle(OrderShipped $event)
    {
        // $event->orderにより、注文へアクセス…
    }
}

lightbulb">Tip!! イベントリスナでも、必要な依存をコンストラクターのタイプヒントで指定できます。イベントリスナは全てLaravelのサービスコンテナで依存解決されるので、依存は自動的に注入されます。{tip} Your event listeners may also type-hint any dependencies they need on their constructors. All event listeners are resolved via the Laravel service container[/docs/{{version}}/container], so dependencies will be injected automatically.

イベントの伝播の停止Stopping The Propagation Of An Event

場合によりイベントが他のリスナへ伝播されるのを止めたいこともあります。その場合はhandleメソッドからfalseを返してください。Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so by returning false from your listener's handle method.

イベントリスナのキュー投入Queued Event Listeners

メール送信やHTTPリクエストを作成するなど、遅い仕事を担当する場合、そのリスナをキューイングできると便利です。キューリスナに取り掛かる前に、キューの設定を確実に行い、サーバかローカル開発環境でキューリスナを起動しておいてください。Queueing listeners can be beneficial if your listener is going to perform a slow task such as sending an e-mail or making an HTTP request. Before getting started with queued listeners, make sure to configure your queue[/docs/{{version}}/queues] and start a queue listener on your server or local development environment.

リスナーをキュー投入するように指定するには、ShouldQueueインターフェイスをリスなクラスに追加します。event:generate Artisanコマンドにより生成したリスナには、既にこのインターフェイスが現在の名前空間下にインポートされていますので、すぐに使用できます。To specify that a listener should be queued, add the ShouldQueue interface to the listener class. Listeners generated by the event:generate Artisan command already have this interface imported into the current namespace, so you can use it immediately:

<?php

namespace App\Listeners;

use App\Events\OrderShipped;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendShipmentNotification implements ShouldQueue
{
    //
}

これだけです!これでこのリスナがイベントのために呼び出されると、Laravelのキューシステムを使い、イベントデスパッチャーにより自動的にキューへ投入されます。キューにより実行されるリスナから例外が投げられなければ、そのキュージョブは処理が済み次第、自動的に削除されます。That's it! Now, when this listener is called for an event, it will be automatically queued by the event dispatcher using Laravel's queue system[/docs/{{version}}/queues]. If no exceptions are thrown when the listener is executed by the queue, the queued job will automatically be deleted after it has finished processing.

キューへの任意アクセスManually Accessing The Queue

リスナの裏で動作しているキュージョブの、deletereleaseメソッドを直接呼び出したければ、Illuminate\Queue\InteractsWithQueueトレイトを使えます。このトレイトは生成されたり砂にはデフォルトとしてインポートされており、これらのメソッドへアクセスできるようになっています。If you need to manually access the listener's underlying queue job's delete and release methods, you may do so using the Illuminate\Queue\InteractsWithQueue trait. This trait is imported by default on generated listeners and provides access to these methods:

<?php

namespace App\Listeners;

use App\Events\OrderShipped;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendShipmentNotification implements ShouldQueue
{
    use InteractsWithQueue;

    public function handle(OrderShipped $event)
    {
        if (true) {
            $this->release(30);
        }
    }
}

イベント発行Firing Events

イベントを発行するには、eventヘルパにそのイベントインスタンスを渡してください。このヘルパはイベントを登録している全リスナに対してディスパッチします。eventヘルパはグローバルに使用できますので、アプリケーションのどこからでも呼び出せます。To fire an event, you may pass an instance of the event to the event helper. The helper will dispatch the event to all of its registered listeners. Since the event helper is globally available, you may call it from anywhere in your application:

<?php

namespace App\Http\Controllers;

use App\Order;
use App\Events\OrderShipped;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    /**
     * 指定した注文を発送
     *
     * @param  int  $orderId
     * @return Response
     */
    public function ship($orderId)
    {
        $order = Order::findOrFail($orderId);

        // 注文発送ロジック…

        event(new OrderShipped($order));
    }
}

lightbulb">Tip!! テスト時には、実際にリスナを起動せずに、イベントが発行されたかをアサートできるようになっています。Laravelの組み込みテストヘルパにより、簡単にテストできます。{tip} When testing, it can be helpful to assert that certain events were fired without actually triggering their listeners. Laravel's built-in testing helpers[/docs/{{version}}/mocking#mocking-events] makes it a cinch.

イベントEvent Subscribers

イベント購読プログラミングWriting Event Subscribers

イベント購読クラスは、その内部で複数のイベントを購読でき、一つのクラスで複数のイベントハンドラを定義できます。購読クラスは、イベントディスパッチャインスタンスを受け取る、subscribeメソッドを定義する必要があります。イベントリスナを登録するには、渡されたディスパッチャのlistenメソッドを呼び出します。Event subscribers are classes that may subscribe to multiple events from within the class itself, allowing you to define several event handlers within a single class. Subscribers should define a subscribe method, which will be passed an event dispatcher instance. You may call the listen method on the given dispatcher to register event listeners:

<?php

namespace App\Listeners;

class UserEventSubscriber
{
    /**
     * ユーザログインイベント処理
     */
    public function onUserLogin($event) {}

    /**
     * ユーザログアウトイベント処理
     */
    public function onUserLogout($event) {}

    /**
     * 購読するリスナの登録
     *
     * @param  Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'Illuminate\Auth\Events\Login',
            'App\Listeners\UserEventSubscriber@onUserLogin'
        );

        $events->listen(
            'Illuminate\Auth\Events\Logout',
            'App\Listeners\UserEventSubscriber@onUserLogout'
        );
    }

}

イベント購読登録Registering Event Subscribers

購読クラスを書いたら、イベントディスパッチャへ登録できる準備が整いました。EventServiceProvider$subscribeプロパティを使用し、購読クラスを登録します。例として、UserEventSubscriberをリストに追加してみましょう。After writing the subscriber, you are ready to register it with the event dispatcher. You may register subscribers using the $subscribe property on the EventServiceProvider. For example, let's add the UserEventSubscriber to the list:

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションのイベントリスナをマップ
     *
     * @var array
     */
    protected $listen = [
        //
    ];

    /**
     * 登録する購読クラス
     *
     * @var array
     */
    protected $subscribe = [
        'App\Listeners\UserEventSubscriber',
    ];
}

章選択

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

設定

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

ヘッダー項目移動

キーボード操作