laravel 学习笔记(三):事件、事件监听器

    技术2022-07-11  114

    (可能是由于理解力的问题,看laravel官方文档还是有点懵的…)

    事件

    比如,【用户登录】事件。

    事件是数据的载体。比如【用户登录】,它要传递的数据就是用户的注册信息,用户名、邮箱等。


    事件监听器

    监听注册事件触发之后要做的事情。比如,在用户登录时触发【用户登录】事件,拿到用户的邮箱地址、登录ip等,用来发送邮件通知用户,你的账号在什么时间什么地点登录了。


    实例

    1.创建UserLogin事件 php artisan make:event UserLogin 生成文件:app/Events/UserLogin.php

    <?php namespace App\Providers; use Illuminate\Auth\Events\Registered; use Illuminate\Auth\Listeners\SendEmailVerificationNotification; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Event; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], ]; /** * Register any events for your application. * * @return void */ public function boot() { parent::boot(); // } }

    2.注册事件监听器 在app/Providers/EventServiceProvider.php

    protected $listen = [ 'App\Events\UserLogin'=>[ 'App\Listeners\DoSomeThing1', 'App\Listeners\DoSomeThing2', ], ];

    3.命令行生成事件监听者 php artisan event:generate 生成文件: app/Listeners/DoSomeThing1.php app/Listeners/DoSomeThing2.php

    4.在控制器中触发事件 php artisan make:controller TestEventController 生成文件:app/Http/Controllers/TestEventController.php

    <?php namespace App\Http\Controllers; use App\Events\UserLogin; use Illuminate\Http\Request; class TestEventController extends Controller { public function index() { event(new UserLogin()); } }

    5.注册路由,访问控制器 routes/web.php

    Route::get('/event', 'TestEventController@index');

    查看日志 [2020-07-01 07:26:02] local.INFO: DoSomeThing1 [2020-07-01 07:26:02] local.INFO: DoSomeThing2

    6.其他 队列异步处理 修改DoSomeThing2.php,继承接口ShouldQueue,并新增 $connection,$queue属性

    <?php namespace App\Listeners; use App\Events\UserLogin; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Support\Facades\Log; class DoSomeThing2 implements ShouldQueue { /** * 队列连接名称 * * @var string */ public $connection = 'database'; /** * 队列名称 * * @var string */ public $queue = 'default'; /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param UserLogin $event * @return void */ public function handle(UserLogin $event) { Log::info('DoSomeThing2'); } }

    再次访问控制器 发现日志只有 [2020-07-01 07:32:37] local.INFO: DoSomeThing1

    要启动队列才能真正执行DoSomeThing2 php artisan queue:work

    查看日志 [2020-07-01 07:33:49] local.INFO: DoSomeThing2

    Processed: 0.009, SQL: 9