Home >Backend Development >PHP Tutorial >Simple application of Laravel 51 events and event listening

Simple application of Laravel 51 events and event listening

WBOY
WBOYOriginal
2016-07-29 09:11:22949browse

?
Laravel 51 事件、事件监听的简单应用

Sometimes when we simply read the Laravel manual, we will have some doubts, such as authorization and events under system services, and what are the application scenarios of these functional services. In fact, if you have not experienced certain Development experienceIt is normal to have these doubts, but when we think more about it at work, we will find that sometimes we have actually seen these services before. Below is a very simple example of events and event monitoring and you will find out.

? This example is about the implementation of the number of views of the article. When the user views the article, the number of views of the article will increase by 1. Viewing the article by the user is an event. With an event, an event listener is needed to monitor the event. After the occurrence, perform the corresponding operation (increase the number of article views by 1). In fact, this monitoring mechanism is implemented in Laravel through the observer mode.

Register events and listeners

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

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

Then execute the following command in the project root directory

<code>php artisan event:generate</code>

After the command is completed, it will automatically be in app respectively The BlogView.php and BlogViewListener.php files are generated in the /Events and app/Listensers directories.

Define events

<code><span><?php</span><span>namespace</span> App\Events<span>;</span><span>use</span> App\Events\Event<span>;</span><span>use</span> App\Post<span>;</span><span>use</span> Illuminate\Queue\SerializesModels<span>;</span><span>use</span> Illuminate\Contracts\Broadcasting\ShouldBroadcast<span>;</span><span>class</span> BlogView <span>extends</span> Event
{
    <span>use</span> SerializesModels<span>;</span><span>/**</span><span>     * Create a new event instance.</span><span>     *</span><span>     * </span><span>@return</span><span> void</span><span>     */</span><span>public</span><span>function</span><span>__construct</span><span>(</span>Post <span>$post</span><span>)</span>
    {
        <span>$this</span>->post = <span>$post</span><span>;</span>
    }

    <span>/**</span><span>     * Get the channels the event should be broadcast on.</span><span>     *</span><span>     * </span><span>@return</span><span> array</span><span>     */</span><span>public</span><span>function</span> broadcastOn<span>()</span>
    {
        <span>return</span><span>[];</span>
    }
}</span></code>

In fact, when you see this, you will find that the event class just injects a Post instance and does not contain redundant logic.

Define the listener

The event listener receives the event instance in the handle method. The event:generate command will automatically import the appropriate event class and type hint event in the handle method. Within the handle method, you can perform any required logic in response to the event. Our code is implemented as follows:

<code><span><?php</span><span>namespace</span> App\Listeners<span>;</span><span>use</span> App\Events\BlogView<span>;</span><span>use</span> Illuminate\Queue\InteractsWithQueue<span>;</span><span>use</span> Illuminate\Contracts\Queue\ShouldQueue<span>;</span><span>use</span> Illuminate\Session\Store<span>;</span><span>class</span> BlogViewListener
{
    <span>protected</span><span>$session</span><span>;</span><span>/**</span><span>     * Create the event listener.</span><span>     *</span><span>     * </span><span>@return</span><span> void</span><span>     */</span><span>public</span><span>function</span><span>__construct</span><span>(</span>Store <span>$session</span><span>)</span>
    {
        <span>$this</span>->session = <span>$session</span><span>;</span>
    }

    <span>/**</span><span>     * Handle the event.</span><span>     *</span><span>     * </span><span>@param</span><span>BlogView</span><span>  $event</span><span>     * </span><span>@return</span><span> void</span><span>     */</span><span>public</span><span>function</span> handle<span>(</span>BlogView <span>$event</span><span>)</span>
    {
        <span>$post</span> = <span>$event</span>->post<span>;</span><span>//先进行判断是否已经查看过</span><span>if</span><span>(</span>!<span>$this</span>->hasViewedBlog<span>(</span><span>$post</span><span>))</span> {
            <span>//保存到数据库</span><span>$post</span>->view_cache = <span>$post</span>->view_cache + <span>1</span><span>;</span><span>$post</span>->save<span>();</span><span>//看过之后将保存到 Session </span><span>$this</span>->storeViewedBlog<span>(</span><span>$post</span><span>);</span>
        }
    }

    <span>protected</span><span>function</span> hasViewedBlog<span>(</span><span>$post</span><span>)</span>
    {
        <span>return</span><span>array_key_exists</span><span>(</span><span>$post</span>->id<span>,</span><span>$this</span>->getViewedBlogs<span>());</span>
    }

    <span>protected</span><span>function</span> getViewedBlogs<span>()</span>
    {
        <span>return</span><span>$this</span>->session->get<span>(</span><span>'viewed_Blogs'</span><span>,</span><span>[]);</span>
    }

    <span>protected</span><span>function</span> storeViewedBlog<span>(</span><span>$post</span><span>)</span>
    {
        <span>$key</span> = <span>'viewed_Blogs.'</span>.<span>$post</span>->id<span>;</span><span>$this</span>->session->put<span>(</span><span>$key</span><span>,</span><span>time</span><span>());</span>
    }

}</span></code>

Some logic has also been explained in the comments.

Trigger event

After the event and event monitoring are completed, what we have to do is to implement the entire monitoring, that is, to trigger the user to open the article event. Here we use the fire method provided by Event, as follows:

<code><span><?php</span><span>namespace</span> App\Http\Controllers<span>;</span><span>use</span> Illuminate\Http\Request<span>;</span><span>use</span> App\Post<span>;</span><span>use</span> Illuminate\Support\Facades\Event<span>;</span><span>use</span> App\Http\Requests<span>;</span><span>use</span> App\Events\BlogView<span>;</span><span>use</span> App\Http\Controllers\Controller<span>;</span><span>class</span> BlogController <span>extends</span> Controller
{
   
    <span>public</span><span>function</span> showPost<span>(</span><span>$slug</span><span>)</span>
    {
        <span>$post</span> = Post::whereSlug<span>(</span><span>$slug</span><span>)</span>->firstOrFail<span>();</span>
        Event::fire<span>(</span><span>new</span> BlogView<span>(</span><span>$post</span><span>));</span><span>return</span> view<span>(</span><span>'home.blog.content'</span><span>)</span>->withPost<span>(</span><span>$post</span><span>);</span>
    }

}</span></code>

Now open the page and find that the `view_cache in the database has been increased by 1 normally, so the whole thing is complete.

The above introduces the simple application of Laravel 51 events and event monitoring, including development experience and mapping relationships. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn