事件和事件監聽器

輕描淡寫發表於2019-09-16

app\Providers\EventServiceProvider.php$listen陣列中中註冊事件和事件監聽器

  protected $listen = [
            Registered::class => [ 
                SendEmailVerificationNotification::class,
            ],
            'App\Events\ArticleViewEvent' => [
                'App\Listeners\ArticleViewListener',
            ],
    ];

在這裡,你只需要將監聽器和事件新增到 EventServiceProvider 中,而後使用 event:generate 命令。這個命令會生成在 EventServiceProvider 中列出的所有事件和監聽器。當然,已經存在的事件和監聽器將保持不變。

php artisan event:generate
 <?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;
use App\Models\Article;

class ArticleViewEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $article;
    /**
     * Create a new event instance.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) void
     */
    public function __construct(Article $article)
    {
        $this->article = $article;
        //
    }

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

namespace App\Listeners;

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

class ArticleViewListener
{
    /**
     * Create the event listener.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) void
     */
    public function __construct(ArticleViewEvent $event)
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ArticleViewEvent  $event
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) void
     */
    public function handle(ArticleViewEvent $event)
    {
        $article = $event->article;
        $article->number = $article->number + 1;
        $article->save();
    }
}
 <?php

namespace App\Http\Controllers;

use App\Models\Article;
use App\Models\Author;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Mail;
use Illuminate\Support\Facades\DB;
use App\Events\ArticleViewEvent;
use Event;
class IndexController extends Controller
{

    public function index(Article $article){
        $post = Article::find(1);
        event(new ArticleViewEvent($post));
    }

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章