基本的な使用法Basic Usage
LaravelのEventクラスはシンプルなオブザーバの実装を提供します。アプリケーションの中でイベントを購読したり、リッスンするために使用します。The Laravel Event class provides a simple observer implementation, allowing you to subscribe and listen for events in your application.
イベントを購読するSubscribing To An Event
Event::listen('auth.login', function($user)
{
$user->last_login = new DateTime;
$user->save();
});
イベントを発行するFiring An Event
$response = Event::fire('auth.login', array($user));
アプリケーションの中で、次に起こすことを制御するために使用できる、レスポンスの配列をfireメソッドは返します。The fire method returns an array of responses that you can use to control what happens next in your application.
優先度を指定し、イベントを購入するSubscribing To Events With Priority
イベントをリッスンする時に優先度を設定することもできます。高い優先度のリスナーは先に実行されます。同じ優先度のリスナーは登録した順番で実行されます。You may also specify a priority when subscribing to events. Listeners with higher priority will be run first, while listeners that have the same priority will be run in order of subscription.
Event::listen('auth.login', 'LoginHandler', 10);
Event::listen('auth.login', 'OtherHandler', 5);
イベントがそれ以上伝わるのを止める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 listener:
Event::listen('auth.login', function($event)
{
// このイベントを処理する...
return false;
});
どこでイベントを登録するかWhere To Register Events
これでイベントをどう登録するかを理解してもらえたと思います。しかし、どこで登録するのか迷っているんではないでしょうか。ご心配なく、よく尋ねられる質問です。残念ながら、答えを出すのは難しいのです。なぜなら、ほとんどどこででも登録できるからです! しかし、いくつかヒントはあります。イベントも、他の起動コードと同様に、app/start/global.phpのようなstartファイルのどれかで登録できます。So, you know how to register events, but you may be wondering where to register them. Don't worry, this is a common question. Unfortunately, it's a hard question to answer because you can register an event almost anywhere! But, here are some tips. Again, like most other bootstrapping code, you may register events in one of your start files such as app/start/global.php.
もしstartファイルが混雑したら、独立したapp/events.phpファイルを作成し、startファイルから読み込みこともできます。これは起動コードの他の部分と明確に分離してイベントを登録する簡単な手法です。If your start files are getting too crowded, you could create a separate app/events.php file that is included from a start file. This is a simple solution that keeps your event registration cleanly separated from the rest of your bootstrapping.
もしクラスベースのアプローチが好みであれば、サービスプロバイダーの中で登録して下さい。本質的にどのアプローチが「正しい」というものではなく、アプリケーションのサイズに基づき、皆さんが好ましいと感じるアプローチを選んで下さい。If you prefer a class based approach, you may register your events in a service provider[/docs/4.2/ioc#service-providers]. Since none of these approaches is inherently "correct", choose an approach you feel comfortable with based on the size of your application.
ワイルドカードリスナーWildcard Listeners
ワイルドカードイベントリスナーを登録するRegistering Wildcard Event Listeners
イベントリスナーを登録する時、アスタリスクを用い、ワイルドカードリスナーを指定することができます。When registering an event listener, you may use asterisks to specify wildcard listeners:
Event::listen('foo.*', function($param)
{
// このイベントを処理する...
});
この場合、リスナーはfoo.で始まるイベント全部を処理します。This listener will handle all events that begin with foo..
実際にどのイベントが発行されたのかを調べるために、Event::firedメソッドが使用できます。You may use the Event::firing method to determine exactly which event was fired:
Event::listen('foo.*', function($param)
{
if (Event::firing() == 'foo.bar')
{
//
}
});
リスナークラスを使用するUsing Classes As Listeners
イベントハンドラーにクロージャーではなく、クラスを使用したい場合もあるでしょう。クラスのイベントハンドラーはLaravelのIoCコンテナによりインスタンスが解決され、これによりリスナーに依存性を注入できる利点があります。In some cases, you may wish to use a class to handle an event rather than a Closure. Class event listeners will be resolved out of the Laravel IoC container[/docs/4.2/ioc], providing you the full power of dependency injection on your listeners.
クラスリスナーを登録するRegistering A Class Listener
Event::listen('auth.login', 'LoginHandler');
イベントリスナークラスを定義するDefining An Event Listener Class
デフォルトでは、LoginHandlerクラスのhandleメソッドが呼び出されます。By default, the handle method on the LoginHandler class will be called:
class LoginHandler {
public function handle($data)
{
//
}
}
リッスンに使用するメソッドを指定するSpecifying Which Method To Subscribe
もしデフォルトのhandleメソッドを使用したくないのでしたら、使用するメソッドを指定してください。If you do not wish to use the default handle method, you may specify the method that should be subscribed:
Event::listen('auth.login', 'LoginHandler@onLogin');
イベントキューQueued Events
イベントキューに登録するRegistering A Queued Event
queueやflushメソッドで、イベントを発行させる"キュー"に登録することができますが、即時に発行されるわけではありません。Using the queue and flush methods, you may "queue" an event for firing, but not fire it immediately:
Event::queue('foo', array($user));
フラッシャーを実行し、全てのキューイベントをフラッシュするにはflushメソッドを使用してください。You may run the "flusher" and flush all queued events using the flush method:
Event::flush('foo');
イベント購読クラス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('auth.login', 'UserEventHandler@onUserLogin');
$events->listen('auth.logout', '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/4.2/ioc] to resolve your subscriber. To do so, simply pass the name of your subscriber to the subscribe method:
Event::subscribe('UserEventHandler');