事件和事件监听器

1. 注册事件和事件监听器#

app\Providers\EventServiceProvider.php$listen 数组中中注册事件和事件监听器

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

2. 生成事件 和 事件监听器#

在这里,你只需要将监听器和事件添加到 EventServiceProvider 中,而后使用 event:generate 命令。这个命令会生成在 EventServiceProvider 中列出的所有事件和监听器。当然,已经存在的事件和监听器将保持不变。

php artisan event:generate

3. 定义事件#

 <?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');
    }
}

4. 定义监听器#

 <?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();
    }
}

5. 事件调用#

 <?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 协议》,转载必须注明作者和本文链接
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。