Laravel 5.1 defines events, event listeners, and triggering event examples

Source: Internet
Author: User
Tags event listener

Here we are based on the Model + cache based on the article to check the deletion of the article after the preservation of the text of the cache to further optimize the processing. We treat the article save (new/modified) as an event that saves the content of the article to the cache and puts it in the listener:

1, registration Events-Listeners

First we need to register the mapping between the event and the Listener in Eventserviceprovider:

The code is as follows Copy Code

protected $listen = [
' App\events\postsaved ' =>[
' App\listeners\savedatatocache '
]
];

Then we run the following artisan command in the project root directory:

PHP Artisan Event:generate

This command generates postsaved.php in the App/events directory and generates savedatatocache.php in the App/listeners directory.

2. Defining event Classes

Next we edit the event class postsaved as follows:

The code is as follows Copy Code

<?php

namespace App\events;

Use app\events\event;
Use App\models\post;
Use Illuminate\queue\serializesmodels;
Use Illuminate\contracts\broadcasting\shouldbroadcast;

Class Postsaved 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 is broadcast on.
*
* @return Array
*/
Public Function Broadcaston ()
{
return [];
}
}

We inject a post instance into the constructor to pass to Postsaved.

3. Define Listener Class

We then define the Listener class Savedatatocache, where the listener class uses the handle method to receive the event instance and execute the business logic that responds to the event, where the post instance received is saved to the cache:

The code is as follows Copy Code

<?php

namespace App\listeners;

Use app\events\postsaved;
Use Cache;
Use Log;
Use Illuminate\queue\interactswithqueue;
Use Illuminate\contracts\queue\shouldqueue;

Class Savedatatocache
{
/**
* Create the event listener.
*
* @return void
*/
Public Function __construct ()
{
//
}

/**
* Handle the event.
*
* @param postsaved $event
* @return void
*/
Public function handle (postsaved $event)
{
$post = $event->post;
$key = ' post_ '. $post->id;
Cache::p ut ($key, $post, 60*24*7);
Log::info (' Save article to cache success! ', [' id ' => $post->id, ' title ' => $post->title]);
}
}

The business logic is simple: Get the story instance from the injected postsaved and save it to the cache, and log the action to the journal.

4. Triggering event

Finally, we'll test the article save events and their listeners.

To trigger the article save event, you can use the fire method provided by the event façade to modify the store method in Postcontroller as follows:

The code is as follows Copy Code

Public function Store (Request $request)
{
$title = $request->input (' title ');
$content = $request->input (' content ');

$post = new Post;
$post->title = $title;
$post->content = $content;
$post->save ();

Event::fire (New postsaved ($post));

Return Redirect ()->route (' Post.show ', [' Post ' => $post]);
}

Then modify the Update method as follows:

  code is as follows copy code

Public Function update (Request $request, $id)
{
    $ Post = Post::find ($id);
    if (! $post)
        exit (' Specifies that the article does not exist! ');

    $title = $request->input (' title ');
    $content = $request->input (' content ');

    $post->title = $title;
    $post->content = $content;
    $post->save ();

    Event::fire (New postsaved ($post));

    return Redirect ()->route (' Post.show ', [' Post ' => $post]);
}

Access Http://laravel.app:8000/post/create in the browser, fill in the title and article content:

Click on the submit page to jump to the article details page, at this point to view the log storage/logs/laravel.log, you can see the corresponding log records:

[2015-11-10 23:14:12] Local.info: Save article to cache success! {"id": "title": "Test Event Add"}
Indicates that the article save event has been triggered and the listener monitors the event and then saves it to the cache and logs the log.

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.