Laravel 51 Simple application of event and event monitoring

Source: Internet
Author: User
Tags event listener
?

Sometimes when we simply look at the Laravel manual there will be some doubts, such as the authorization and events under the system service, what are the application scenarios of these functional services, in fact, if you have not experienced a certain development experience have these doubts is very normal things, But when we think more about our work, we can see that sometimes we've seen these services in fact. Here's a very simple example of event and event monitoring, and you'll find out.

? This example is about the implementation of the number of views of the article, when the user view the article when the number of articles will be increased by 1, the user to view the article is an event, with the event, you need an event listener, to listen to the event after the execution of the corresponding operation (article views and 1), in fact, this monitoring mechanism in Laravel is implemented through the observer pattern.

Registering events and listeners

First we need to app/Providers/ EventServiceProvider.php register the event Listener mapping relationship in the directory, as follows:

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

Then execute the following command under the project root directory

php artisan event:generate

When the command is completed, it will automatically app/Events app/Listensers generate and file in the and directory respectively BlogView.php BlogViewListener.php .

Defining events


   namespaceApp\events; UseApp\events\event; UseApp\post; UseIlluminate\queue\serializesmodels; UseIlluminate\contracts\broadcasting\shouldbroadcast;classBlogviewextendsevent{ UseSerializesmodels;/*** Create A new event instance.     *     * @returnvoid     */ Publicfunction__construct(Post$post){$this->post =$post;}/*** Get The channels the event should is broadcast on.     *     * @returnArray     */ PublicfunctionBroadcaston(){return[];}}

Actually seeing these you will find that the event class just injects an Post instance of it, and does not contain extraneous logic.

Defining listeners

The event listener handle receives the event instance in the method, and the Event:generate command automatically imports the appropriate event class and type hint events in the handle method. handlewithin the method, you can execute any required logic in response to the event, and our code is implemented as follows:


   namespaceApp\listeners; UseApp\events\blogview; UseIlluminate\queue\interactswithqueue; UseIlluminate\contracts\queue\shouldqueue; UseIlluminate\session\store;classblogviewlistener{protected$session;/*** Create the event listener.     *     * @returnvoid     */ Publicfunction__construct(Store$session){$this->session =$session;}/*** Handle the event.     *     * @paramBlogview$event     * @returnvoid     */ PublicfunctionHandle(Blogview$event){$post=$event->post;//First make a decision whether you have viewedif(!$this->hasviewedblog($post)){//Save to database$post->view_cache =$post->view_cache +1;$post->save();//After viewing will be saved to Session$this->storeviewedblog($post);}    }protectedfunctionHasviewedblog($post){returnarray_key_exists($post->id,$this->getviewedblogs());}protectedfunctionGetviewedblogs(){return$this->session->get(' Viewed_blogs ',[]);}protectedfunctionStoreviewedblog($post){$key=' Viewed_blogs. '.$post->id;$this->session->put($key, Time());}}

Some logic has also been explained in the comments.

Triggering events

After the event and event monitoring is complete, all we have to do is implement the entire listener, that is, trigger the user to open the article event here we use and Event provide the fire method as follows:

 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{ publicfunction showPost($slug) { $post = Post::whereSlug($slug)->firstOrFail(); Event::fire(new BlogView($post));return view('home.blog.content')->withPost($post); }}

Now open the page found in the database of the ' View_cache has been normal add 1, so the whole is done.

The above describes the Laravel 51 event, event monitoring of the simple application, including the development experience, mapping the relationship of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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: info-contact@alibabacloud.com 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.