Simple application of Laravel51 event and Event Monitoring

Source: Internet
Author: User
: This article mainly introduces the simple application of Laravel51 events and event listening. For more information about PHP tutorials, see. ?

Sometimes when we simply lookLaravelThere will be some questions in the manual, such as the authorization and events under the system service. What are the application scenarios of these functional services?Development ExperienceIt is normal to have these questions, but when we think more at work, we will find that sometimes we have seen these services all the time. The following is a simple example of event and event monitoring.

? This example is about the implementation of the number of articles. when a user views an article, the number of articles browsed increases by 1. when a user views an article, it is an event with an event, an event listener is required to perform corresponding operations on the event to be monitored (article browsing Shujia 1). In fact, this listening mechanism isLaravelIs implemented through the observer mode.

Register events and listeners

First, we needapp/Providers/DirectoryEventServiceProvider.phpRegistering event listenersIng, As follows:

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

Run the following command in the project Root Directory:

php artisan event:generate

After the command is completed,app/EventsAndapp/ListensersDirectory generationBlogView.phpAndBlogViewListener.phpFile.

Define events

  post = $post;    }    /**     * Get the channels the event should be broadcast on.     *     * @return array     */publicfunction broadcastOn()    {        return[];    }}

In fact, you will find that the event class only injectsPostThe instance does not contain any redundant logic.

Define listener

The event listener is inhandleThe event: generate command automatically imports the appropriate event classes and types in the handle method. InhandleIn the method, you can execute any required logic to respond to the event. our code implementation is as follows:

  Session = $ session;}/*** Handle the event. ** @ paramBlogView $ event * @ return void */publicfunction handle (BlogView $ event) {$ post = $ event-> post; // First, determine whether the if (! $ This-> hasViewedBlog ($ post) {// save to database $ post-> view_cache = $ post-> view_cache + 1; $ post-> save (); // save it to Session $ this-> storeViewedBlog ($ post) ;}} protectedfunction hasViewedBlog ($ post) {returnarray_key_exists ($ post-> id, $ this-> getViewedBlogs ();} protectedfunction getViewedBlogs () {return $ this-> session-> get ('viewed _ Blogs ', []);} protectedfunction storeViewedBlog ($ post) {$ key = 'viewed _ Blogs. '. $ post-> id; $ this-> session-> put ($ key, time ());}}

Some logic is also described in the annotations.

Trigger Event

After the event and event listening are complete, all we need to do is implement the whole listening, that is, trigger the user to open the article event here we useEventProvidedfireThe method is as follows:

  firstOrFail();        Event::fire(new BlogView($post));return view('')->withPost($post);    }}

Open the page and you will find that the 'view _ cache in the database has been properly added with 1, so the whole process is complete.

The above introduces the simple applications of Laravel 51 events and event listening, including development experience and ing relationships, and hopes to help those who are interested in PHP tutorials.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

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.