Laravel 5.1 事件、事件监听的简单应用

bVqBce

​ 有时候当咱们单纯的看 Laravel 手册的时候会有一些疑惑,好比说系统服务下的受权和事件,这些功能服务的应用场景是什么,其实若是没有经历过必定的开发经验有这些疑惑是很正常的事情,可是当咱们在工做中多加思考会发现有时候这些服务其实咱们一直都见过。下面就事件、事件监听举一个很简单的例子你就会发现。php

​ 这个例子是关于文章的浏览数的实现,当用户查看文章的时候文章的浏览数会增长1,用户查看文章就是一个事件,有了事件,就须要一个事件监听器,对监听的事件发生后执行相应的操做(文章浏览数加1),其实这种监听机制在 Laravel 中是经过观察者模式实现的.laravel

注册事件以及监听器

首先咱们须要在 app/Providers/目录下的EventServiceProvider.php中注册事件监听器映射关系,以下:数据库

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

而后项目根目录下执行以下命令session

php artisan event:generate

该命令完成后,会分别自动在 app/Eventsapp/Listensers目录下生成 BlogView.phpBlogViewListener.php文件。app

定义事件

<?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实例罢了,并无包含多余的逻辑。ide

定义监听器

事件监听器在handle方法中接收事件实例,event:generate命令将会自动在handle方法中导入合适的事件类和类型提示事件。在handle方法内,你能够执行任何须要的逻辑以响应事件,咱们的代码实现以下:post

<?php

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());
    }

}

注释中也已经说明了一些逻辑。this

触发事件

事件和事件监听完成后,咱们要作的就是实现整个监听,即触发用户打开文章事件在此咱们使用和 Event提供的 fire方法,以下:spa

<?php

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了,这样整个就完成了。code

相关文章
相关标签/搜索