事件服务提供者中配置

  1. protected $listen = [
  2. Registered::class => [
  3. SendEmailVerificationNotification::class,
  4. ],
  5. 'App\Events\Test' => [
  6. 'App\Listeners\DoSomething1',
  7. 'App\Listeners\DoSomething2',
  8. ],
  9. ];

生成对应的事件类和监听器

php artisan event::generate 自动生成目录和对应的事件类和监听器,生成的目录结构

image.png

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class Test
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $message;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($msg)
    {
        // 事件接收一个信息
        $this->message = $msg;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
<?php

namespace App\Listeners;

use App\Events\Test;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class DoSomething1 implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Test  $event
     * @return void
     */
    public function handle(Test $event)
    {
        //
        echo "DoSomething handle event";
        info('do something');
    }
}
<?php

namespace App\Listeners;

use App\Events\Test;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class DoSomething2
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Test  $event
     * @return void
     */
    public function handle(Test $event)
    {
        // 使用 $event->message 来访问信息 ...
        echo "SendShipmentNotification handle event".$event->message;
        Log::info($event->message);
    }
}

事件触发

Route::get("/event",function (){
    // 实例化是传入参数,事件类接受,由之后的监听器处理
    event(new \App\Events\Test("我是你的好兄弟")); 
});

监听器队列

在监听器中设置队列的链接和队列名称

/**
 * 任务将被发送到的连接的名称
 *
 * @var string|null
 */
public $connection = 'redis';

/**
 * 任务将被发送到的队列的名称
 *
 * @var string|null
 */
public $queue = 'DoSomething';

使用队列需要 实现ShouldQueue接口 use Illuminate\Contracts\Queue\ShouldQueue
跟普通的没有其他区别

事件触发一样,但要使监听生效,需要运行 php artisan queue:work