Laravel 5.1 事件、事件監聽的容易應用

來源:互聯網
上載者:User
Laravel 5.1 事件、事件監聽的簡單應用

?

有時候當我們單純的看 Laravel 手冊的時候會有一些疑惑,比如說系統服務下的授權和事件,這些功能服務的應用情境是什麼,其實如果沒有經曆過一定的開發經驗有這些疑惑是很正常的事情,但是當我們在工作中多加思考會發現有時候這些服務其實我們一直都見過。下面就事件、事件監聽舉一個很簡單的例子你就會發現。

? 這個例子是關於文章的瀏覽數的實現,當使用者查看文章的時候文章的瀏覽數會增加1,使用者查看文章就是一個事件,有了事件,就需要一個事件監聽器,對監聽的事件發生後執行相應的操作(文章瀏覽數加1),其實這種監聽機制在 Laravel 中是通過觀察者模式實現的.

註冊事件以及監聽器

首先我們需要在 app/Providers/目錄下的EventServiceProvider.php中註冊事件監聽器映射關係,如下:

protected $listen = [        'App\Events\BlogView' => [            'App\Listeners\BlogViewListener',        ],    ];

然後項目根目錄下執行如下命令

php artisan event:generate

該命令完成後,會分別自動在 app/Eventsapp/Listensers目錄下產生 BlogView.phpBlogViewListener.php檔案。

定義事件

namespace 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方法內,你可以執行任何需要的邏輯以響應事件,我們的代碼實現如下:

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)    {        $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方法,如下:

namespace 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了,這樣整個就完成了。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.