事件和事件监听器

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 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!