首頁  >  文章  >  後端開發  >  詳解如何利用Laravel事件系統實現登入日誌

詳解如何利用Laravel事件系統實現登入日誌

*文
*文原創
2018-01-02 17:23:212683瀏覽

如何利用Laravel事件系統實作登入日誌?本文主要為大家介紹了利用Laravel事件系統如何實現登入日誌記錄的相關資料,文中介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。希望對大家有幫助。

下面來看看詳細的介紹:

#明確需求

記錄一個登入日誌,通常需要下列資訊:

  • 客戶端Agent資訊

  • #客戶端IP位址

  • 存取IP地點

  • 登入時間

  • 登入使用者資訊

##已建立工具

明確完需求後,就依照每個需求找出自己所需的工具吧。


  • 需求1 jenssegers/agent就可以滿足我們要求

  • 需求2 Laravel下直接

    Request::getClientIp( )

  • 需求3 zhuzhichao/ip-location-zh這個套件可以滿足要求

  • 需求4 time()

  • 需求5 登入使用者模型


#開工

採用Laravel的事件訂閱系統來實現,需要實作一個登入事件和一個登入事件監聽器。


產生事件和監聽器

Laravel命令列支援自動產生事件和監聽器,在App\Providers\EventServiceProvider中新增需要實現的事件:

protected $listen = [ 
  ...,
  //添加登录事件及对应监听器,一个事件可绑定多个监听器
  'App\Events\LoginEvent' => [
  'App\Listeners\LoginListener',
 ],
];

執行指令:

php artisan event:generate就會自動產生事件和監聽器,已存在的事件和監聽器不會改變。

登入事件(Event)

回顧下需求,我們的登入事件需要的5點信息,在事件中需要記錄這些信息,所以事件設計如下:

namespace App\Events;

use Illuminate\Broadcasting\Channel; 
use Illuminate\Queue\SerializesModels; 
use Illuminate\Broadcasting\PrivateChannel; 
use Illuminate\Foundation\Events\Dispatchable; 
use Illuminate\Broadcasting\InteractsWithSockets;

use App\Models\User; 
use Jenssegers\Agent\Agent;

class LoginEvent 
{
     use Dispatchable, InteractsWithSockets, SerializesModels;
    
     /**
     * @var User 用户模型
     */
     protected $user;
    
     /**
     * @var Agent Agent对象
     */
     protected $agent;
    
     /**
     * @var string IP地址
     */
     protected $ip;
    
     /**
     * @var int 登录时间戳
     */
     protected $timestamp;
    
     /**
     * 实例化事件时传递这些信息
     */
     public function __construct($user, $agent, $ip, $timestamp)
     {
         $this->user = $user;
         $this->agent = $agent;
         $this->ip = $ip;
         $this->timestamp = $timestamp;
     }
    
     public function getUser()
     {
         return $this->user;
     }
    
     public function getAgent()
     {
         return $this->agent;
     }
    
     public function getIp()
     {
         return $this->ip;
     }
    
     public function getTimestamp()
     {
         return $this->timestamp;
     }
    
     /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
     public function broadcastOn()
     {
         return new PrivateChannel('channel-default');
     }
}

在事件中記錄所需的信息,並實作這些資訊的get方法。


登入監聽器(Listener)

在監聽器中,取得到事件傳遞過來的信息,把這些資訊記錄到資料庫中,實作如下:

namespace App\Listeners;

use App\Events\LoginEvent;

class LoginListener 
{

     // handle方法中处理事件
     public function handle(LoginEvent $event)
     {
     //获取事件中保存的信息
     $user = $event->getUser();
     $agent = $event->getAgent();
     $ip = $event->getIp();
     $timestamp = $event->getTimestamp();
    
     //登录信息
     $login_info = [
      'ip' => $ip,
      'login_time' => $timestamp,
      'user_id' => $user->id
     ];
    
     // zhuzhichao/ip-location-zh 包含的方法获取ip地理位置
     $addresses = \Ip::find($ip);
     $login_info['address'] = implode(' ', $addresses);
    
     // jenssegers/agent 的方法来提取agent信息
     $login_info['device'] = $agent->device(); //设备名称
     $browser = $agent->browser();  
     $login_info['browser'] = $browser . ' ' . $agent->version($browser); //浏览器
     $platform = $agent->platform();
     $login_info['platform'] = $platform . ' ' . $agent->version($platform); //操作系统
     $login_info['language'] = implode(',', $agent->languages()); //语言
     //设备类型
     if ($agent->isTablet()) {
      // 平板
      $login_info['device_type'] = 'tablet';
     } else if ($agent->isMobile()) {
      // 便捷设备
      $login_info['device_type'] = 'mobile';
     } else if ($agent->isRobot()) {
      // 爬虫机器人
      $login_info['device_type'] = 'robot';
      $login_info['device'] = $agent->robot(); //机器人名称
     } else {
      // 桌面设备
      $login_info['device_type'] = 'desktop';
     }
    
     //插入到数据库
     DB::table('login_log')->insert($login_info);
    
     } 
}

這樣,監聽器就完成了,每次一觸發登入事件,就會在資料庫中加入一條登入資訊。


觸發事件

透過全域的

event()方法來觸發事件,event()方法的參數為事件實例:

namespace App\Controllers; 
...
use App\Events\LoginEvent; 
use Jenssegers\Agent\Agent; 
class AuthControoler extends Controller 
{
 ...
 public function login(Request $request)
 {
 //登录实现
 ...
 //登录成功,触发事件
 event(new LoginEvent($this->guard()->user(), new Agent(), \Request::getClientIp(), time()));
 ... 
 } 
}

佇列化監聽器

有時監聽器會進行一些耗時操作,這時應該結合Laravel的佇列系統將監聽器進行佇列化,前提是已經配置了佇列並開啟了佇列處理器。


佇列化非常簡單,只需監聽器實作ShouldQueue介面即可,即:

namespace App\Listeners; 
...
use Illuminate\Contracts\Queue\ShouldQueue; 
class LoginListener implements ShouldQueue 
{
     /**
     * 失败重试次数
     * @var int
     */
     public $tries = 1;
     ...
}

總結

Laravel的事件系統實現起來還是非常優雅的,同一個事件可以很方便的添加各類監聽器,且各個監聽器之間互不干擾,解耦性非常強。加上隊列系統,可以很方便的處理一些後續任務。

相關推薦:

探究Laravel的中間件是如何實現的

講解如何在laravel中自訂加密服務

#提升Laravel 5效能的一些實用技巧

以上是詳解如何利用Laravel事件系統實現登入日誌的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn