?
有時候當我們單純的看 Laravel
手冊的時候會有一些疑惑,比如說系統服務下的授權和事件,這些功能服務的應用場景是什么,其實如果沒有經歷過一定的開發經驗有這些疑惑是很正常的事情,但是當我們在工作中多加思考會發現有時候這些服務其實我們一直都見過。下面就事件、事件監聽舉一個很簡單的例子你就會發現。
? 這個例子是關于文章的瀏覽數的實現,當用戶查看文章的時候文章的瀏覽數會增加1,用戶查看文章就是一個事件,有了事件,就需要一個事件監聽器,對監聽的事件發生后執行相應的操作(文章瀏覽數加1),其實這種監聽機制在 Laravel
中是通過觀察者模式實現的.
首先我們需要在 app/PRoviders/
目錄下的EventServiceProvider.php
中注冊事件監聽器映射關系,如下:
protected $listen = [ 'App/Events/BlogView' => [ 'App/Listeners/BlogViewListener', ], ];
然后項目根目錄下執行如下命令
php artisan event:generate
該命令完成后,會分別自動在 app/Events
和app/Listensers
目錄下生成 BlogView.php
和BlogViewListener.php
文件。
<?phpnamespace App/Events;use App/Events/Event;use App/Post;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(Post $post) { $this->post = $post; } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return []; }}
其實看到這些你會發現該事件類只是注入了一個 Post
實例罷了,并沒有包含多余的邏輯。
事件監聽器在handle
方法中接收事件實例,event:generate命令將會自動在handle方法中導入合適的事件類和類型提示事件。在handle
方法內,你可以執行任何需要的邏輯以響應事件,我們的代碼實現如下:
<?phpnamespace 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) { $post = $event->post; //先進行判斷是否已經查看過 if (!$this->hasViewedBlog($post)) { //保存到數據庫 $post->view_cache = $post->view_cache + 1; $post->save(); //看過之后將保存到 Session $this->storeViewedBlog($post); } } protected function hasViewedBlog($post) { return array_key_exists($post->id, $this->getViewedBlogs()); } protected function getViewedBlogs() { return $this->session->get('viewed_Blogs', []); } protected function storeViewedBlog($post) { $key = 'viewed_Blogs.'.$post->id; $this->session->put($key, time()); }}
注釋中也已經說明了一些邏輯。
事件和事件監聽完成后,我們要做的就是實現整個監聽,即觸發用戶打開文章事件在此我們使用和 Event
提供的 fire
方法,如下:
<?phpnamespace App/Http/Controllers;use Illuminate/Http/Request;use App/Post;use Illuminate/Support/Facades/Event;use App/Http/Requests;use App/Events/BlogView;use App/Http/Controllers/Controller;class BlogController extends Controller{ public function showPost($slug) { $post = Post::whereSlug($slug)->firstOrFail(); Event::fire(new BlogView($post)); return view('home.blog.content')->withPost($post); }}
現在打開頁面發現數據庫中的`view_cache已經正常加1了,這樣整個就完成了。
新聞熱點
疑難解答