laravel中的事件与监听器

在工作中,你是否经常遇到这种情况:某些业务的逻辑变动频繁,无论如何抽象service来解耦合,controller中的代码还是无可避免地走向屎山。这时就是到了观察者模式出场的时候,laravel中得event与listener已经优雅的实现了该模式。

<?php

namespace App\Events;

use App\Models\Mission;
use App\Models\User;
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 MissionAccomplished
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public User $user;
    public Mission $mission;

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

    /**
     * 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\MissionAccomplished;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

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

    /**
     * Handle the event.
     *
     * @param  \App\Events\MissionAccomplished  $event
     * @return void
     */
    public function handle(MissionAccomplished $event)
    {
        $mission = $event->mission;
        $user = $event->user;
        #TODO 实现发放奖励的逻辑
        Log::info("[{$user->nickname}]领取了任务[{$mission->name}]奖励");
    }
}

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注