App\Providers\EventServiceProvider
添加protected $listen = [
'App\Events\BlogView' => [
'App\Listeners\BlogViewListener',
],
];
php artisan event:generate
在 App\Events
和 App\Listeners
会生成对应的文件
public $post_id;
public function __construct($post_id)
{
$this->post_id = $post_id;
}
public function handle(BlogView $event)
{
$post_id = $event->post_id;
logger('文章-'.$post_id . "被查看");
//可以统计文章阅读次数(把viewCount+1),这里简便起见用的 logger
}
class BlogController extends Controller
{
public function index($id)
{
//调用触发器
event(new BlogView($id));
}
}