【发布时间】:2015-02-01 12:15:09
【问题描述】:
所以我正在尝试新的 Laravel 5 Event 方法。
在我的存储库中,我正在触发事件“KitchenStored”:
// Events
use App\Events\KitchenStored;
class EloquentKitchen implements KitchenInterface {
public function store($input) {
$kitchen = new $this->kitchen;
$kitchen->name = $input['name'];
$kitchen->save();
\Event::fire(new KitchenStored($kitchen));
return $kitchen;
}
哪个成功触发了这个事件:
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class KitchenStored extends Event {
use SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($kitchen)
{
$this->kitchen = $kitchen;
}
}
但是,它没有链接到这个处理程序:
<?php namespace App\Handlers\Events;
use App\Events\KitchenStored;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class AttachCurrentUserToKitchen {
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
dd('handler');
}
/**
* Handle the event.
*
* @param KitchenStored $event
* @return void
*/
public function handle(KitchenStored $event)
{
//
}
}
我知道是因为 dd('handler');在请求生命周期内不会触发。
我已在此处向其侦听器注册了该事件:
<?php namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider {
/**
* The event handler mappings for the application.
*
* @var array
*/
protected $listen = [
App\Events\KitchenStored::class => [
App\Handlers\Events\AttachCurrentUserToKitchen::class
]
];
/**
* Register any other events for your application.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
Event::listen('App\Events\KitchenStored',
'App\Handlers\Events\AttachCurrentUserToKitchen');
}
}
谁能更好地解释这个过程,以便我可以继续使用迄今为止最简洁的代码?
非常感谢
【问题讨论】:
标签: php events laravel laravel-5