事件和事件监听器
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 协议》,转载必须注明作者和本文链接
推荐文章: