事件类通常被保存在 app/Events 目录下,而它们的处理程序则被保存在 app/Handlers/Events 目录下。
php artisan make:event CqhTestEvent
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class CqhTestEvent extends Event {
use SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
}
}
event(new CqhTestEvent());
$response = Event::fire(new CqhTestEvent());
php artisan handler:event CqhTestEventHandler --event=CqhTestEvent
<?php namespace App\Handlers\Events;
use App\Events\CqhTestEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class CqhTestEventHandler {
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param CqhTestEvent $event
* @return void
*/
public function handle(CqhTestEvent $event)
{
//
}
}
public function handle(CqhTestEvent $event)
{
//
echo ‘chenqionghe的事件被处理了‘;
}
<?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 = [
‘event.name‘ => [
‘EventListener‘,
],
//在这里加上
‘App\Events\CqhTestEvent‘ => [
‘App\Handlers\Events\CqhTestEventHandler‘,
],
];
...
}
Event::listen(‘App\Events\CqhTestEvent‘, ‘App\Handlers\Events\CqhTestEventHandler‘);
Event::listen(‘App\Events\CqhTestEvent‘, function($event)
{
// 处理事件...
});
public function getTest()
{
Event::listen(‘App\Events\CqhTestEvent‘, function($event)
{
echo ‘触发事件1‘;
});
Event::listen(‘App\Events\CqhTestEvent‘, function($event)
{
echo ‘触发事件2‘;
});
Event::listen(‘App\Events\CqhTestEvent‘, function($event)
{
echo ‘触发事件3‘;
});
event(new CqhTestEvent());
}
触发事件1触发事件2触发事件3
public function getTest()
{
Event::listen(‘App\Events\CqhTestEvent‘, function($event)
{
echo ‘触发事件1‘;
});
Event::listen(‘App\Events\CqhTestEvent‘, function($event)
{
echo ‘触发事件2‘;
return false;
});
Event::listen(‘App\Events\CqhTestEvent‘, function($event)
{
echo ‘触发事件3‘;
});
event(new CqhTestEvent());
}
触发事件1触发事件2
原文:http://www.cnblogs.com/chenqionghe/p/4884390.html