1、注册事件以及监听器
首先我们需要在 app/Providers/目录下的EventServiceProvider.php中注册事件监听器映射关系,如下:
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], //上面是框架自带 'AppEventsBlogView' => [ 'AppListenersBlogViewListener', ], ];
然后项目根目录下执行如下命令 php artisan event:generate 该命令完成后,会分别自动在 app/Events和app/Listensers目录下生成 BlogView.php和BlogViewListener.php文件。
2、定义事件
在 app/Events/目录下的BlogView.php中定义事件,在__construct()的参数填写我们需要操作的类。如下:
<?php namespace AppEvents; use IlluminateBroadcastingChannel; use IlluminateQueueSerializesModels; use IlluminateBroadcastingPrivateChannel; use IlluminateBroadcastingPresenceChannel; use IlluminateFoundationEventsDispatchable; use IlluminateBroadcastingInteractsWithSockets; use IlluminateContractsBroadcastingShouldBroadcast; use AppModelAdminArticleModel; class BlogView { use Dispatchable, InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct(ArticleModel $article) { $this->article = $article; } /** * Get the channels the event should broadcast on. * * @return IlluminateBroadcastingChannel|array */ public function broadcastOn() { return new PrivateChannel('channel-name'); } }
3、定义监听
在 app/Listeners/目录下的BlogViewListener.php中,在handle()的处理业务逻辑。如下:
<?php namespace AppListeners; use AppEventsBlogView; use IlluminateQueueInteractsWithQueue; use IlluminateContractsQueueShouldQueue; class BlogViewListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param BlogView $event * @return void */ public function handle(BlogView $event) { $event->article->where('art_id', '=', $event->article->art_id)->increment('clicks'); //点击自增//保存数据库 } }
4、触发事件
<?php namespace AppHttpControllersHome; use AppEventsBlogView; use IlluminateSupportFacadesEvent; use AppModelAdminArticleModel; use AppModelAdminCategoryModel; use IlluminateHttpRequest; class IndexController extends CommonController { public function article(Request $request, $id){ $articleModel = new ArticleModel(); // $articleModel->where('art_id', '=', $id)->increment('clicks'); //点击自增 $data = $articleModel->findOrFail($id); $categoryModel = new CategoryModel(); $cate = $categoryModel->parentTree($data->cate_id); //获取上级分类 $pre = $articleModel->where([['cate_id','=',$data->cate_id],['art_id','<',$id]])->first(); //获取上一篇文章 $next = $articleModel->where([['cate_id','=',$data->cate_id],['art_id','>',$id]])->first(); $relation = $articleModel->where('cate_id', '=', $data->cate_id)->get(); //获取相关文章 Event::dispatch(new BlogView($data)); //通过查看源码,Event::fire 更改为Event::dispatch // event(new BlogView($data)); return View('home.new',compact('data','cate','pre', 'next', 'relation')); } }
其他关于事件的操作,如队列。
链接:https://laravelacademy.org/post/19508.html