事件 如文章瀏覽數,用戶關注等這些動做均可以稱做事件,經過事件監聽,而後對監聽事件執行(如更新瀏覽數,關注人數等)相應的操做php
1.在 app/Providers/EventServiceProvider.php中註冊事件監聽器映射關係sql
protected $listen = [ 'App\Events\BlogView' => [ //事件 'App\Listeners\BlogViewListener', //事件監聽 ], // 'App\Events\SomeEvent' => [ 可多個事件,事件監聽 // 'App\Listeners\EventListener', // ], ];
2.執行命令 生成事件文件和事件監聽文件 數據庫
php artisan event:generate
注:該命令完成後,會分別自動在 app/Events和app/Listensers目錄下生成 BlogView.php和BlogViewListener.php文件。session
3.事件
app
<?php namespace App\Events; use App\Events\Event; use App\Blog;//模型 use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; 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 []; } }
注:僅構造函數中將模型當作實例傳入ide
4.事件監聽函數
<?php namespace App\Listeners; use App\Events\BlogView; //引入事件 use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Session\Store; 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.控制器中應用事件監聽this
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Blog; use Illuminate\Support\Facades\Event; use App\Http\Requests; use App\Events\BlogView; //引入事件監聽 use App\Http\Controllers\Controller; class BlogController extends Controller { public function show() { $blog = Blog::where('id',1)->first(); //實例 Event::fire(new BlogView($blog)); } }
6.相關的代碼spa
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;
路由blog
//事件,註冊,監聽 Route::get('blog/show','BlogController@show');