Readouble

Laravel 8.x イベント

イントロダクションIntroduction

Laravelのイベントは、単純なオブザーバーパターンの実装を提供し、アプリケーション内で発生するさまざまなイベントをサブスクライブしてリッスンできるようにします。イベントクラスは通常、app/Eventsディレクトリに保存し、リスナはapp/Listenersに保存します。Artisanコンソールコマンドを使用してイベントとリスナを生成すると、これらのディレクトリが作成されるため、アプリケーションにこれらのディレクトリが表示されていなくても心配ありません。Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within 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 as they will be created for you as you generate events and listeners using Artisan console commands.

1つのイベントに、相互に依存しない複数のリスナを含めることができるため、イベントは、アプリケーションのさまざまな側面を分離するための優れた方法として機能します。たとえば、注文が発送されるたびにユーザーにSlack通知を送信したい場合があります。注文処理コードをSlack通知コードに結合する代わりに、リスナが受信してSlack通知をディスパッチするために使用できるApp\Events\OrderShippedイベントを発生させることができます。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 raise an App\Events\OrderShipped event which a listener can receive and use to dispatch a Slack notification.

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

Laravelアプリケーションに含まれているApp\Providers\EventServiceProviderは、アプリケーションのすべてのイベントリスナを登録するための便利な場所を提供しています。listenプロパティには、すべてのイベント(キー)とそのリスナ(値)の配列が含まれています。アプリケーションが必要とするイベントをこの配列へ全部追加できます。例として、OrderShippedイベントを追加してみましょう。The App\Providers\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). You may add as many events to this array as your application requires. For example, let's add an OrderShipped event:

use App\Events\OrderShipped;
use App\Listeners\SendShipmentNotification;

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

lightbulb">Tip!! event:listコマンドを使用して、アプリケーションによって登録されたすべてのイベントとリスナのリストを表示できます。{tip} The event:list command may be used to display a list of all events and listeners registered by your application.

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

もちろん、各イベントとリスナのファイルを一つずつ手で生成するのは面倒です。代わりに、リスナとイベントをEventServiceProviderへ追加し、event:generate Artisanコマンドを使用してください。このコマンドは、EventServiceProviderにリストされているまだ存在しないイベントとリスナを生成します。Of course, manually creating the files for each event and listener is cumbersome. Instead, add listeners and events to your EventServiceProvider and use the event:generate Artisan command. This command will generate any events or listeners that are listed in your EventServiceProvider that do not already exist:

php artisan event:generate

もしくは、make:eventコマンドとmake:listener Artisanコマンドを使用して、個々のイベントとリスナを生成することもできます。Alternatively, you may use the make:event and make:listener Artisan commands to generate individual events and listeners:

php artisan make:event PodcastProcessed

php artisan make:listener SendPodcastNotification --event=PodcastProcessed

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

通常、イベントはEventServiceProvider$listen配列を介して登録する必要があります。ただし、EventServiceProviderbootメソッドでクラスまたはクロージャベースのイベントリスナを手動で登録することもできます。Typically, events should be registered via the EventServiceProvider $listen array; however, you may also register class or closure based event listeners manually in the boot method of your EventServiceProvider:

use App\Events\PodcastProcessed;
use App\Listeners\SendPodcastNotification;
use Illuminate\Support\Facades\Event;

/**
 * アプリケーションの他の全イベントの登録
 *
 * @return void
 */
public function boot()
{
    Event::listen(
        PodcastProcessed::class,
        [SendPodcastNotification::class, 'handle']
    );

    Event::listen(function (PodcastProcessed $event) {
        //
    });
}

Queueable匿名イベントリスナQueueable Anonymous Event Listeners

クロージャベースのイベントリスナを手動で登録する場合、リスナクロージャをIlluminate\Events\queueable関数内にラップして、キューを使用してリスナを実行するようにLaravelへ指示できます。When registering closure based event listeners manually, you may wrap the listener closure within the Illuminate\Events\queueable function to instruct Laravel to execute the listener using the queue[/docs/{{version}}/queues]:

use App\Events\PodcastProcessed;
use function Illuminate\Events\queueable;
use Illuminate\Support\Facades\Event;

/**
 * アプリケーションの他の全イベントの登録
 *
 * @return void
 */
public function boot()
{
    Event::listen(queueable(function (PodcastProcessed $event) {
        //
    }));
}

キュー投入ジョブと同様に、onConnectiononQueuedelayメソッドを使用して、キュー投入するリスナの実行をカスタマイズできます。Like queued jobs, you may use the onConnection, onQueue, and delay methods to customize the execution of the queued listener:

Event::listen(queueable(function (PodcastProcessed $event) {
    //
})->onConnection('redis')->onQueue('podcasts')->delay(now()->addSeconds(10)));

キューに投入した匿名リスナの失敗を処理したい場合は、queueableリスナを定義するときにcatchメソッドにクロージャを指定できます。このクロージャは、リスナの失敗の原因となったイベントインスタンスとThrowableインスタンスを受け取ります。If you would like to handle anonymous queued listener failures, you may provide a closure to the catch method while defining the queueable listener. This closure will receive the event instance and the Throwable instance that caused the listener's failure:

use App\Events\PodcastProcessed;
use function Illuminate\Events\queueable;
use Illuminate\Support\Facades\Event;
use Throwable;

Event::listen(queueable(function (PodcastProcessed $event) {
    //
})->catch(function (PodcastProcessed $event, Throwable $e) {
    // キュー投入したリスナは失敗した…
}));

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

ワイルドカードパラメータとして*を使用してリスナを登録することもでき、同じリスナで複数のイベントをキャッチできます。ワイルドカードリスナは、最初の引数としてイベント名を受け取り、2番目の引数としてイベントデータ配列全体を受け取ります。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 event name as their first argument and the entire event data array as their second argument:

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

イベントディスカバリーEvent Discovery

EventServiceProvider$listen配列にイベントとリスナを手動で登録する代わりに、自動イベント検出を有効にすることもできます。イベント検出が有効になっている場合、LaravelはアプリケーションのListenersディレクトリをスキャンすることでイベントとリスナを自動的に見つけて登録します。さらに、EventServiceProviderにリストされている明示的に定義されたイベントは引き続き登録します。Instead of registering events and listeners manually in the $listen array of the EventServiceProvider, you can enable automatic event discovery. When event discovery is enabled, Laravel will automatically find and register your events and listeners by scanning your application's Listeners directory. In addition, any explicitly defined events listed in the EventServiceProvider will still be registered.

Laravelは、PHPのリフレクションサービスを使用してリスナクラスをスキャンすることにより、イベントリスナを見つけます。Laravelがhandleで始まるリスナクラスメソッドを見つけると、Laravelはそれらのメソッドをメソッドの引数でタイプヒントされているイベントのイベントリスナとして登録します。Laravel finds event listeners by scanning the listener classes using PHP's reflection services. When Laravel finds any listener class method that begins with handle, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature:

use App\Events\PodcastProcessed;

class SendPodcastNotification
{
    /**
     * 指定イベントの処理
     *
     * @param  \App\Events\PodcastProcessed  $event
     * @return void
     */
    public function handle(PodcastProcessed $event)
    {
        //
    }
}

イベント検出はデフォルトで無効になっていますが、アプリケーションのEventServiceProvidershouldDiscoverEventsメソッドをオーバーライドすることで有効にできます。Event discovery is disabled by default, but you can enable it by overriding the shouldDiscoverEvents method of your application's EventServiceProvider:

/**
 * イベントとリスナを自動的に検出するかを判定
 *
 * @return bool
 */
public function shouldDiscoverEvents()
{
    return true;
}

デフォルトでは、アプリケーションのapp/Listenersディレクトリ内のすべてのリスナをスキャンします。スキャンする追加のディレクトリを定義する場合は、EventServiceProviderdiscoverEventsWithinメソッドをオーバーライドしてください。By default, all listeners within your application's app/Listeners directory will be scanned. If you would like to define additional directories to scan, you may override the discoverEventsWithin method in your EventServiceProvider:

/**
 * イベントの検出に使用するリスナディレクトリを取得
 *
 * @return array
 */
protected function discoverEventsWithin()
{
    return [
        $this->app->path('Listeners'),
    ];
}

実働環境でのイベント検出Event Discovery In Production

本番環境では、フレームワークがすべてのリクエストですべてのリスナをスキャンするのは効率的ではありません。したがって、デプロイメントプロセス中に、event:cache Artisanコマンドを実行して、アプリケーションのすべてのイベントとリスナのマニフェストをキャッシュする必要があります。このマニフェストは、イベント登録プロセスを高速化するためにフレームワークか使用します。event:clearコマンドを使用してキャッシュを破棄できます。In production, it is not efficient for the framework to scan all of your listeners on every request. Therefore, during your deployment process, you should run the event:cache Artisan command to cache a manifest of all of your application's events and listeners. This manifest will be used by the framework to speed up the event registration process. The event:clear command may be used to destroy the cache.

イベント定義Defining Events

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

<?php

namespace App\Events;

use App\Models\Order;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OrderShipped
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * 注文インスタンス
     *
     * @var \App\Models\Order
     */
    public $order;

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

ご覧のとおり、このイベントクラスにはロジックが含まれていません。購読したApp\Models\Orderインスタンスのコンテナです。イベントで使用されるSerializesModelsトレイトは、キュー投入するリスナを利用する場合など、イベントオブジェクトがPHPのserialize関数を使用してシリアル化される場合、Eloquentモデルを適切にシリアル化します。As you can see, this event class contains no logic. It is a container for the App\Models\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, such as when utilizing queued listeners[#queued-event-listeners].

リスナ定義Defining Listeners

次に、サンプルイベントのリスナを見てみましょう。イベントリスナは、handleメソッドでイベントインスタンスを受け取ります。event:generatemake:listener Artisanコマンドは、適切なイベントクラスを自動的にインポートし、handleメソッドでイベントをタイプヒントします。handleメソッド内で、イベントに応答するために必要なアクションを実行できます。Next, let's take a look at the listener for our example event. Event listeners receive event instances in their handle method. The event:generate and make:listener Artisan commands 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  \App\Events\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 email or making an HTTP request. Before using queued listeners, make sure to configure your queue[/docs/{{version}}/queues] and start a queue worker on your server or local development environment.

リスナをキューに投入するように指定するには、ShouldQueueインターフェイスをリスナクラスに追加します。event:generatemake:listener Artisanコマンドによって生成されたリスナには、このインターフェイスが現在の名前空間にインポートされているため、すぐに使用できます。To specify that a listener should be queued, add the ShouldQueue interface to the listener class. Listeners generated by the event:generate and make:listener Artisan commands 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 an event handled by this listener is dispatched, the listener will automatically be 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.

キュー接続とキュー名のカスタマイズCustomizing The Queue Connection & Queue Name

イベントリスナのキュー接続、キュー名、またはキュー遅延時間をカスタマイズする場合は、リスナクラスで$connection$queue$delayプロパティを定義できます。If you would like to customize the queue connection, queue name, or queue delay time of an event listener, you may define the $connection, $queue, or $delay properties on your listener class:

<?php

namespace App\Listeners;

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

class SendShipmentNotification implements ShouldQueue
{
    /**
     * ジョブの送信先となる接続名
     *
     * @var string|null
     */
    public $connection = 'sqs';

    /**
     * ジョブの送信先となるキュー名
     *
     * @var string|null
     */
    public $queue = 'listeners';

    /**
     * ジョブを処理するまでの時間(秒)
     *
     * @var int
     */
    public $delay = 60;
}

実行時にリスナのキュー接続またはキュー名を定義したい場合は、リスナにviaConnectionまたはviaQueueメソッドを定義します。If you would like to define the listener's queue connection or queue name at runtime, you may define viaConnection or viaQueue methods on the listener:

/**
 * リスナのキュー接続の名前の取得
 *
 * @return string
 */
public function viaConnection()
{
    return 'sqs';
}

/**
 * リスナのキュー名を取得
 *
 * @return string
 */
public function viaQueue()
{
    return 'listeners';
}

条件付き投入リスナConditionally Queueing Listeners

場合によっては、実行時にのみ使用可能なデータに基づいて、リスナをキュー投入する必要があるかどうかを判断する必要が起きるでしょう。このために、shouldQueueメソッドをリスナに追加して、リスナをキュー投入する必要があるかどうかを判断できます。shouldQueueメソッドがfalseを返す場合、リスナは実行されません。Sometimes, you may need to determine whether a listener should be queued based on some data that are only available at runtime. To accomplish this, a shouldQueue method may be added to a listener to determine whether the listener should be queued. If the shouldQueue method returns false, the listener will not be executed:

<?php

namespace App\Listeners;

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

class RewardGiftCard implements ShouldQueue
{
    /**
     * ギフトカードを顧客へ提供
     *
     * @param  \App\Events\OrderCreated  $event
     * @return void
     */
    public function handle(OrderCreated $event)
    {
        //
    }

    /**
     * リスナをキューへ投入するかを決定
     *
     * @param  \App\Events\OrderCreated  $event
     * @return bool
     */
    public function shouldQueue(OrderCreated $event)
    {
        return $event->order->subtotal >= 5000;
    }
}

キューの手動操作Manually Interacting With The Queue

リスナの基になるキュージョブのdeleteメソッドとreleaseメソッドへ手動でアクセスする必要がある場合は、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\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SendShipmentNotification implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * イベントの処理
     *
     * @param  \App\Events\OrderShipped  $event
     * @return void
     */
    public function handle(OrderShipped $event)
    {
        if (true) {
            $this->release(30);
        }
    }
}

キュー投入するイベントリスナとデータベーストランザクションQueued Event Listeners & Database Transactions

キュー投入したリスナがデータベーストランザクション内でディスパッチされると、データベーストランザクションがコミットされる前にキューによって処理される場合があります。これが発生した場合、データベーストランザクション中にモデルまたはデータベースレコードに加えた更新は、データベースにまだ反映されていない可能性があります。さらに、トランザクション内で作成されたモデルまたはデータベースレコードは、データベースに存在しない可能性があります。リスナがこれらのモデルに依存している場合、キューに入れられたリスナをディスパッチするジョブの処理時に予期しないエラーが発生する可能性があります。When queued listeners are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your listener depends on these models, unexpected errors can occur when the job that dispatches the queued listener is processed.

キュー接続のafter_commit設定オプションがfalseに設定されている場合でも、リスナクラスで$afterCommitプロパティを定義することにより、開いているすべてのデータベーストランザクションがコミットされた後に、特定のキューに入れられたリスナをディスパッチする必要があることを示すことができます。If your queue connection's after_commit configuration option is set to false, you may still indicate that a particular queued listener should be dispatched after all open database transactions have been committed by defining an $afterCommit property on the listener class:

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SendShipmentNotification implements ShouldQueue
{
    use InteractsWithQueue;

    public $afterCommit = true;
}

lightbulb">Tip!! こうした問題の回避方法の詳細は、キュー投入されるジョブとデータベーストランザクションに関するドキュメントを確認してください。{tip} To learn more about working around these issues, please review the documentation regarding queued jobs and database transactions[/docs/{{version}}/queues#jobs-and-database-transactions].

失敗したジョブの処理Handling Failed Jobs

キュー投入したイベントリスナが失敗する場合があります。キュー投入したリスナがキューワーカーによって定義された最大試行回数を超えると、リスナ上のfailedメソッドが呼び出されます。failedメソッドは、失敗の原因となったイベントインスタンスとThrowableを受け取ります。Sometimes your queued event listeners may fail. If queued listener exceeds the maximum number of attempts as defined by your queue worker, the failed method will be called on your listener. The failed method receives the event instance and the Throwable that caused the failure:

<?php

namespace App\Listeners;

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

class SendShipmentNotification implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * イベントの処理
     *
     * @param  \App\Events\OrderShipped  $event
     * @return void
     */
    public function handle(OrderShipped $event)
    {
        //
    }

    /**
     * ジョブの失敗を処理
     *
     * @param  \App\Events\OrderShipped  $event
     * @param  \Throwable  $exception
     * @return void
     */
    public function failed(OrderShipped $event, $exception)
    {
        //
    }
}

キュー投入したリスナの最大試行回数の指定Specifying Queued Listener Maximum Attempts

キュー投入したリスナの1つでエラーが発生した場合、リスナが無期限に再試行し続けることを皆さんも望まないでしょう。そのため、Laravelはリスナを試行できる回数または期間を指定するさまざまな方法を提供しています。If one of your queued listeners is encountering an error, you likely do not want it to keep retrying indefinitely. Therefore, Laravel provides various ways to specify how many times or for how long a listener may be attempted.

リスナクラスで$trysプロパティを定義して、リスナが失敗したと見なされるまでに試行できる回数を指定できます。You may define $tries property on your listener class to specify how many times the listener may be attempted before it is considered to have failed:

<?php

namespace App\Listeners;

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

class SendShipmentNotification implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * キュー投入したリスナが試行される回数
     *
     * @var int
     */
    public $tries = 5;
}

リスナが失敗するまでに試行できる回数を定義する代わりに、リスナをそれ以上試行しない時間を定義することもできます。これにより、リスナは特定の時間枠内で何度でも試行します。リスナの試行最長時間を定義するには、リスナクラスにretryUntilメソッドを追加します。このメソッドはDateTimeインスタンスを返す必要があります:As an alternative to defining how many times a listener may be attempted before it fails, you may define a time at which the listener should no longer be attempted. This allows a listener to be attempted any number of times within a given time frame. To define the time at which a listener should no longer be attempted, add a retryUntil method to your listener class. This method should return a DateTime instance:

/**
 * リスナタイムアウト時間を決定
 *
 * @return \DateTime
 */
public function retryUntil()
{
    return now()->addMinutes(5);
}

イベント発行Dispatching Events

イベントをディスパッチするには、イベントで静的なdispatchメソッドを呼び出します。このメソッドはIlluminate\Foundation\Events\Dispatchableトレイトにより、イベントで使用可能になります。dispatchメソッドに渡された引数はすべて、イベントのコンストラクタへ渡されます。To dispatch an event, you may call the static dispatch method on the event. This method is made available on the event by the Illuminate\Foundation\Events\Dispatchable trait. Any arguments passed to the dispatch method will be passed to the event's constructor:

<?php

namespace App\Http\Controllers;

use App\Events\OrderShipped;
use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;

class OrderShipmentController extends Controller
{
    /**
     * 指定注文を発送
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $order = Order::findOrFail($request->order_id);

        // 注文出荷ロジック…

        OrderShipped::dispatch($order);
    }
}

lightbulb">Tip!! テスト時は、特定のイベントが実際にリスナを起動せずにディスパッチされたことを宣言できると役立つでしょう。Laravelの組み込みのテストヘルパで簡単にできます。{tip} When testing, it can be helpful to assert that certain events were dispatched without actually triggering their listeners. Laravel's built-in testing helpers[/docs/{{version}}/mocking#event-fake] makes it a cinch.

イベントサブスクライバEvent Subscribers

イベントサブスクライバの記述Writing Event Subscribers

イベントサブスクライバは、サブスクライバクラス自体から複数のイベントを購読できるクラスであり、単一のクラス内で複数のイベントハンドラを定義できます。サブスクライバは、イベントディスパッチャーインスタンスを渡すsubscribeメソッドを定義する必要があります。特定のディスパッチャ上のlistenメソッドを呼び出して、イベントリスナを登録します。Event subscribers are classes that may subscribe to multiple events from within the subscriber 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;

use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;

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

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

    /**
     * サブスクライバのリスナを登録
     *
     * @param  \Illuminate\Events\Dispatcher  $events
     * @return void
     */
    public function subscribe($events)
    {
        $events->listen(
            Login::class,
            [UserEventSubscriber::class, 'handleUserLogin']
        );

        $events->listen(
            Logout::class,
            [UserEventSubscriber::class, 'handleUserLogout']
        );
    }
}

イベントリスナのメソッドがサブスクライバ自身の中で定義されている場合は、サブスクライバのsubscribeメソッドからメソッド名とイベントの配列を返す方が便利でしょう。Laravelはイベントリスナを登録する際に、サブスクライバのクラス名を自動的に決定します。If your event listener methods are defined within the subscriber itself, you may find it more convenient to return an array of events and method names from the subscriber's subscribe method. Laravel will automatically determine the subscriber's class name when registering the event listeners:

<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;

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

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

    /**
     * サブスクライバのリスナを登録
     *
     * @param  \Illuminate\Events\Dispatcher  $events
     * @return array
     */
    public function subscribe($events)
    {
        return [
            Login::class => 'handleUserLogin',
            Logout::class => 'handleUserLogout',
        ];
    }
}

イベントサブスクライバの登録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 App\Listeners\UserEventSubscriber;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

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

    /**
     * 登録するサブスクライバクラス
     *
     * @var array
     */
    protected $subscribe = [
        UserEventSubscriber::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!…]形式の挿入削除行の表示形式です。

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

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作