这篇文章给大家介绍如何在laravel中使用事件系统统计浏览量,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
1、在 app\Providers\EventServiceProvider
中注册监听器:
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ ...... 'App\Events\Statistics' => [ 'App\Listeners\BehavioralStatistics', ], ...... ];
2、执行
php artisan event:generate
生成事件类与监听类
3、定义事件
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class Statistics { use Dispatchable, InteractsWithSockets, SerializesModels; public $user; public $obj; /** * Create a new event instance. * * @return void */ public function __construct($user,$obj) { $this->user = $user; $this->obj = $obj; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new PrivateChannel('channel-name'); } }
4、定义监听器:
<?php namespace App\Listeners; use App\Events\Statistics; use App\System\StaticsView; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Log; class BehavioralStatistics { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param Statistics $event * @return void */ public function handle(Statistics $event) { $obj_class = get_class($event->obj); $statics_view = new StaticsView; switch($obj_class){ case "App\\User": $statics_view->statics_type = 'user'; break; case "App\\Production": $statics_view->statics_type = 'production'; break; } $statics_view->ip = request()->getClientIp();; $statics_view->time_local = 0; $statics_view->statics_id = $event->obj->id; $statics_view->save(); } }
5、触发事件:
event(new Statistics(user, user,user,production));
关于如何在laravel中使用事件系统统计浏览量就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。