laravel进阶——事件与监听实现服务解耦

先mark:

事件与监听

https://laravelacademy.org/post/8355.html

事件之观察者模式

https://laravelacademy.org/post/9788.html

 

 

 

编辑 app/Providers/EventServiceProvider.php

 protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        'App\Events\KiwiEvent' => [
            'App\Listeners\ListenOne',
            'App\Listeners\ListenTwo'
        ],
        'App\Events\KiwiTestEvent' => [
            'App\Listeners\ListenLogOne',
            'App\Listeners\ListenLogTwo',
            'App\Listeners\ListenLogThree'
        ]
];

注意

停止事件继续往下传播

有时候,你希望停止事件被传播到其它监听器,你可以通过从监听器的handle  方法中返回 false 来实现。

上面的监听器就要注意顺序了,ListenLogOne return false 后, 后面的监听器不会执行

 

 

生成事件/监听器类

配置好EventServiceProvider 后自动生成Event文件和Listens文件

php artisan event:generate

定义事件

编辑 app/Events/KiwiTestEvent.php

<?php 
namespace App\Events; 

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

class KiwiTestEvent { 
    use Dispatchable, InteractsWithSockets, SerializesModels; 

    public $user; 
    public $type; 

    /** 
    * Create a new event instance. 
    * 
    * @return void 
    */ 
    public function __construct($user, $type) { 
        $this->user = $user;
        $this->type = $type;
    }

    /**
     * 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\KiwiTestEvent;
use Illuminate\Queue\InteractsWithQueue; 
use Illuminate\Contracts\Queue\ShouldQueue; 

class ListenLogThree { 

    public function __construct() { 
        // 
    } 

    /** 
    * Handle the event. 
    * 
    * @param KiwiTestEvent $event 
    * @return void 
    */ 
    public function handle(KiwiTestEvent $event) { 
        print_r($event->user);
        print_r($event->type);
    }
}

 

分发事件

使用助手函数event

public function tt(){
    $users = DB::table('users')->where('id', '>' ,2)->limit(2)->get()->toArray();
    event(new KiwiTestEvent($users, 'mk'));
}