Laravel 的事件系统

  1. App\Providers\EventServiceProvider 添加
protected $listen = [
        'App\Events\BlogView' => [
            'App\Listeners\BlogViewListener',
        ],
    ];
  1. 执行如下命令
php artisan event:generate

App\EventsApp\Listeners 会生成对应的文件

  1. 事件 BlogView
    public $post_id;

    public function __construct($post_id)
    {
        $this->post_id = $post_id;
    }
  1. 监听器 BlogViewListener
    public function handle(BlogView $event)
    {
        $post_id = $event->post_id;
        logger('文章-'.$post_id . "被查看");
        //可以统计文章阅读次数(把viewCount+1),这里简便起见用的 logger
    }
  1. 触发事件
class BlogController extends Controller
{
    public function index($id)
    {
        //调用触发器
        event(new BlogView($id));
    }
}
Build by Loppo 0.5.1