事件及事件监听

事件 如文章浏览数,用户关注等这些动作都可以称作事件,通过事件监听,然后对监听事件执行(如更新浏览数,关注人数等)相应的操作

1.在 app/Providers/EventServiceProvider.php中注册事件监听器映射关系

protected $listen = [
   
    'App\Events\BlogView' => [  //事件
        'App\Listeners\BlogViewListener', //事件监听
    ],
    // 'App\Events\SomeEvent' => [       可多个事件,事件监听
    //     'App\Listeners\EventListener',
    // ],
];

2.执行命令 生成事件文件和事件监听文件 

php artisan event:generate

 注:该命令完成后,会分别自动在 app/Events和app/Listensers目录下生成 BlogView.php和BlogViewListener.php文件。

3.事件

<?php

namespace App\Events;

use App\Events\Event;
use App\Blog;//模型
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(Blog $blog)
    {
        $this->blog = $blog;
    }

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

 注:仅构造函数中将模型当做实例传入

4.事件监听

<?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)
    {
        $blog = $event->blog;
        //先进行判断是否已经查看过
        if (!$this->hasViewedBlog($blog)) {
            //保存到数据库
            $blog->view_cache = $blog->view_cache + 10;
            $blog->save();
            //看过之后将保存到 Session 
            $this->storeViewedBlog($blog);
        }
    }

    protected function hasViewedBlog($blog)
    {
        return array_key_exists($blog->id, $this->getViewedBlogs());
    }

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

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

}

5.控制器中应用事件监听

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Blog;
use Illuminate\Support\Facades\Event;
use App\Http\Requests;
use App\Events\BlogView; //引入事件监听
use App\Http\Controllers\Controller;

class BlogController extends Controller
{
   
    public function show()
    {
        $blog = Blog::where('id',1)->first(); //实例
        Event::fire(new BlogView($blog));
       
    }

}

6.相关的代码

CREATE TABLE `blog` (
  `id` int(11) NOT NULL,
  `title` varchar(30) NOT NULL COMMENT '标题',
  `view_cache` smallint(6) NOT NULL COMMENT '访问次数',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

路由

//事件,注册,监听
Route::get('blog/show','BlogController@show');

 

posted @ 2016-08-22 15:31  东歌  阅读(315)  评论(0编辑  收藏  举报