基本的な使用法Basic Usage
Laravelのイベント機能は、シンプルなオブザーバの実装を提供します。アプリケーションの中でイベントを購読したり、リッスンするために使用します。イベントクラスは通常、app/Events
ディレクトリーへ保存され、ハンドラーはapp/Handlers/Events
に設置します。The Laravel event facilities
provides a simple observer implementation, allowing
you to subscribe and listen for events in your
application. Event classes are typically stored in
the app/Events
directory, while their
handlers are stored in
app/Handlers/Events
.
新しいイベンクラスは、Artisan CLIツールを使用して生成します。You can generate a new event class using the Artisan CLI tool:
php artisan make:event PodcastWasPurchased
イベントを購入するSubscribing To An Event
Laravelアプリケーションに含まれているEventServiceProvider
は、全イベントハンドラーを登録するための便利な手段を提供しています。listen
プロパティは全イベント(キー)とハンドラー(値)で構成されている配列です。もちろん、アプリケーションで必要とされているイベントをこの配列に好きなだけ追加できます。例えば、PodcastWasPurchased
イベントを追加してみましょう。The
EventServiceProvider
included with your
Laravel application provides a convenient place to
register all event handlers. The listen
property contains an array of all events (keys) and
their handlers (values). Of course, you may add as
many events to this array as your application
requires. For example, let's add our
PodcastWasPurchased
event:
/**
* アプリケーションのイベントハンドラーをマップする
*
* @var array
*/
protected $listen = [
'App\Events\PodcastWasPurchased' => [
'App\Handlers\Events\EmailPurchaseConfirmation@handle',
],
];
イベントハンドラーを生成するには、handler:event
Artisan
CLIコマンドを使用します。To generate a
handler for an event, use the
handler:event
Artisan CLI
command:
php artisan handler:event EmailPurchaseConfirmation --event=PodcastWasPurchased
ハンドラーやイベントが必要になるごとに毎回、make:event
やhandler:event
コマンドを実行するのは、もちろん手間がかかります。代わりに、ハンドラーとイベントをEventServiceProvider
に追加し、event:generate
コマンドを使いましょう。このコマンドはEventServiceProvider
にリストしてあるイベントやハンドラーを生成してくれます。Of course, manually running the
make:event
and
handler:event
commands each time you
need a handler or event is cumbersome. Instead,
simply add handlers and events to your
EventServiceProvider
and use the
event:generate
command. This command
will generate any events or handlers that are listed
in your
EventServiceProvider
:
php artisan event:generate
イベントの発行Firing An Event
これで、Event
ファサードを使用し、イベントを発行する用意ができました。Now we are ready to fire our
event using the Event
facade:
$response = Event::fire(new PodcastWasPurchased($podcast));
アプリケーションの中で、次に起きることをコントロールするために、fire
メソッドはレスポンスの配列を返します。The fire
method
returns an array of responses that you can use to
control what happens next in your
application.
イベントを起こすために、event
ヘルパを使用することもできます。You may also use the
event
helper to fire an
event:
event(new PodcastWasPurchased($podcast));
クロージャーのリスナーClosure Listeners
イベントを購読するために、独立したクラスを作成する必要は全くありません。例えば、EventServiceProvider
のboot
メソッドの中で、以下のように指定できます。You can even listen to events
without creating a separate handler class at all.
For example, in the boot
method of your
EventServiceProvider
, you could do the
following:
Event::listen('App\Events\PodcastWasPurchased', function($event)
{
// イベントの処理…
});
イベントの伝播を止めるStopping The Propagation Of An Event
場合により、イベントが他のリスナーへ伝播されるのを止めたいこともあります。ハンドラーから、false
を返してください。Sometimes, you may wish to stop
the propagation of an event to other listeners. You
may do so using by returning false
from
your handler:
Event::listen('App\Events\PodcastWasPurchased', function($event)
{
// イベントの処理…
return false;
});
キュー済みイベントハンドラーQueued Event Handlers
イベントハンドラーを[キュー]queueに投入する必要があるのですか?ハンドラを生成する時に、--queued
フラッグを付けるだけです。Need to
queue[/docs/master/queues] an event handler?
It couldn't be any easier. When generating the
handler, simply use the --queued
flag:
php artisan handler:event SendPurchaseConfirmation --event=PodcastWasPurchased --queued
これにより、ハンドラクラスへIlluminate\Contracts\Queue\ShouldBeQueued
インターフェイスが実装されます。これだけです!これで、このハンドラーがイベントにより呼び出されると、イベントデスパッチャーにより自動的にキューへ投入されます。This will generate a handler
class that implements the
Illuminate\Contracts\Queue\ShouldBeQueued
interface. That's it! Now when this handler is
called for an event, it will be queued automatically
by the event dispatcher.
キューされたハンドラーの実行時に、例外が投げられなければ、そのキューは処理後自動的に削除されます。もし、delete
やrelease
メソッドへ手動でアクセスする必要があれば、どうぞそうしてください。デフォルトでキューハンドラーに含まれている、Illuminate\Queue\InteractsWithQueue
トレイトが、それらのメソッドへのアクセスを提供しています。If no exceptions are thrown when
the handler is executed by the queue, the queued job
will be deleted automatically after it has
processed. If you need to access the queued job's
delete
and release
methods
manually, you may do so. The
Illuminate\Queue\InteractsWithQueue
trait, which is included by default on queued
handlers, gives you access to these
methods:
public function handle(PodcastWasPurchased $event)
{
if (true)
{
$this->release(30);
}
}
既に存在しているハンドラーをキューへ投入するハンドラーへ変更したい場合は、ShouldBeQueued
インターフェイスをそのクラスに追加するだけです。If you have an existing handler
that you would like to convert to a queued handler,
simply add the ShouldBeQueued
interface
to the class manually.
イベント購読クラスEvent Subscribers
イベント購読クラスを定義するDefining An Event Subscriber
イベント購読クラスは一つのクラスで多くのイベントをリッスンするためのものです。購買クラスは、イベントデスパッチャーインスタンスが渡されるsubscribe
メソッドを実装しなくてはなりません。Event subscribers are classes
that may subscribe to multiple events from within
the class itself. Subscribers should define a
subscribe
method, which will be passed
an event dispatcher instance:
class UserEventHandler {
/**
* ユーザーログインイベントの処理
*/
public function onUserLogin($event)
{
//
}
/**
* ユーザーログアウトイベントの処理
*/
public function onUserLogout($event)
{
//
}
/**
* イベント購入リスナーの登録
*
* @param Illuminate\Events\Dispatcher $events
* @return array
*/
public function subscribe($events)
{
$events->listen('App\Events\UserLoggedIn', 'UserEventHandler@onUserLogin');
$events->listen('App\Events\UserLoggedOut', 'UserEventHandler@onUserLogout');
}
}
イベント購入クラスを登録するRegistering An Event Subscriber
イベント購読クラスを定義したら、Event
クラスで登録しましょう。Once the subscriber has been
defined, it may be registered with the
Event
class.
$subscriber = new UserEventHandler;
Event::subscribe($subscriber);
また、LaravelのIoCコンテナを使用し、購読クラスを依存解決したい場合もあるでしょう。その場合でも、ただsubscribe
メソッドへ、購読クラスの登録名を渡すだけです。You may also use the Laravel
IoC container[/docs/ioc] to resolve your
subscriber. To do so, simply pass the name of your
subscriber to the subscribe
method:
Event::subscribe('UserEventHandler');