最近有一個商城項目中有統計商品點擊量和藝術家訪問量的需求,但又不想改動太多原來的代碼,而點擊與訪問這兩個動作是有明確觸發點的,正好可以用laravel中的事件系統來做,在點擊和訪問對應的函數中產生這倆事件,監視器獲取到之后,再將記錄保存到數據庫中,并更新計數。
1、在 app\Providers\EventServiceProvider
中注冊監聽器:
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ ...... 'App\Events\Statistics' => [ 'App\Listeners\BehavioralStatistics' , ], ...... ]; |
2、執行
1
|
php artisan event:generate |
生成事件類與監聽類
3、定義事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<?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、定義監聽器:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
<?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、觸發事件:
1
|
event( new Statistics(user, user,user,production)); |
以上這篇laravel 使用事件系統統計瀏覽量的實現就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/hhhzua/article/details/80635808