添加event监听者
在\app\Providers
目录下EventServiceProvider.php
文件,添加事件和监听者的映射。
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
// 新增事件
'App\Events\AsyncNotifyEvent' => [
'App\Listeners\AsyncEmailNotifyEventListener',// 发送邮件通知
'App\Listeners\AsyncMassageNotifyEventListener',// 发送短信通知
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
生成监听者类
$ php artisan event:generate
Events and listeners generated successfully!
生成两个文件AsyncEmailNotifyEventListener.php
和 AsyncMassageNotifyEventListener.php
$ tree
.
├── AsyncEmailNotifyEventListener.php
├── AsyncMassageNotifyEventListener.php
└── EventListener.php
添加处理逻辑
我们这里添加记录日志方式测试
AsyncEmailNotifyEventListener
<?php
namespace App\Listeners;
use App\Events\AsyncNotifyEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class AsyncEmailNotifyEventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param AsyncNotifyEvent $event
* @return void
*/
public function handle(AsyncNotifyEvent $event)
{
\Log::info("Async_Email_Notify_Event_Listener OK!");
}
}
AsyncMassageNotifyEventListener
<?php
namespace App\Listeners;
use App\Events\AsyncNotifyEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class AsyncMassageNotifyEventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param AsyncNotifyEvent $event
* @return void
*/
public function handle(AsyncNotifyEvent $event)
{
\Log::info("Async_Massage_Notify_Event_Listener OK!");
}
}
测试
我们这里采用路由测试
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
// 测试事件执行
Route::get('/event_test', function () {
\Event::fire(new \App\Events\AsyncNotifyEvent());
return 'success~';
});
访问路由
$ curl http://localhost:8084/event_test
success~
查看日志
$ cat ./storage/logs/laravel.log
[2019-03-13 08:35:01] local.INFO: Async_Email_Notify_Event_Listener OK!
[2019-03-13 08:35:01] local.INFO: Async_Massage_Notify_Event_Listener OK!
完结散花~~
网友评论