事件 如文章浏览数,用户关注等这些动作都可以称作事件,通过事件监听,然后对监听事件执行(如更新浏览数,关注人数等)相应的操作
1.在 app/Providers/EventServiceProvider.php中注册事件监听器映射关系
protected $listen = [ 'AppEventsBlogView' => [ //事件 'AppListenersBlogViewListener', //事件监听 ], // 'AppEventsSomeEvent' => [ 可多个事件,事件监听 // 'AppListenersEventListener', // ], ];
2.执行命令 生成事件文件和事件监听文件
php artisan event:generate
注:该命令完成后,会分别自动在 app/Events和app/Listensers目录下生成 BlogView.php和BlogViewListener.php文件。
3.事件
<?php namespace AppEvents; use AppEventsEvent; use AppBlog;//模型 use IlluminateQueueSerializesModels; use IlluminateContractsBroadcastingShouldBroadcast; class BlogView extends Event { use SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct(Blog $blog) { $this->blog = $blog; } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return []; } }
注:仅构造函数中将模型当做实例传入
4.事件监听
<?php namespace AppListeners; use AppEventsBlogView; //引入事件 use IlluminateQueueInteractsWithQueue; use IlluminateContractsQueueShouldQueue; use IlluminateSessionStore; class BlogViewListener { protected $session; /** * Create the event listener. * * @return void */ public function __construct(Store $session) { $this->session = $session; } /** * Handle the event. * * @param BlogView $event * @return void */ public function handle(BlogView $event) { $blog = $event->blog; //先进行判断是否已经查看过 if (!$this->hasViewedBlog($blog)) { //保存到数据库 $blog->view_cache = $blog->view_cache + 10; $blog->save(); //看过之后将保存到 Session $this->storeViewedBlog($blog); } } protected function hasViewedBlog($blog) { return array_key_exists($blog->id, $this->getViewedBlogs()); } protected function getViewedBlogs() { return $this->session->get('viewed_Blogs', []); } protected function storeViewedBlog($blog) { $key = 'viewed_Blogs.'.$blog->id; $this->session->put($key, time()); } }
5.控制器中应用事件监听
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppBlog; use IlluminateSupportFacadesEvent; use AppHttpRequests; use AppEventsBlogView; //引入事件监听 use AppHttpControllersController; class BlogController extends Controller { public function show() { $blog = Blog::where('id',1)->first(); //实例 Event::fire(new BlogView($blog)); } }
6.相关的代码
CREATE TABLE `blog` ( `id` int(11) NOT NULL, `title` varchar(30) NOT NULL COMMENT '标题', `view_cache` smallint(6) NOT NULL COMMENT '访问次数', `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
路由
//事件,注册,监听 Route::get('blog/show','BlogController@show');