ferdiunal/eloquent-history

Eloquent模型历史跟踪,适用于Laravel

v1.0.0 2023-04-02 12:36 UTC

This package is auto-updated.

Last update: 2024-10-01 00:08:28 UTC


README

Composer

Laravel 9.x及更高版本

composer require ferdiunal/history

config/app.php

'providers' => [
    ...
    Ferdiunal\History\HistoryServiceProvider::class,
];
'aliases' => [
    ...
    'App\History' => Ferdiunal\History\History::class,
];

迁移

php artisan vendor:publish --provider="Ferdiunal\History\HistoryServiceProvider" --tag=migrations

配置

php artisan vendor:publish --provider="Ferdiunal\History\HistoryServiceProvider" --tag=config

本地化

php artisan vendor:publish --provider="Ferdiunal\History\HistoryServiceProvider" --tag=translations

使用方法

HasOperations特质添加到用户模型。

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Ferdiunal\History\HasOperations;

class User extends Authenticatable
{
    use Notifiable, SoftDeletes, HasOperations;
}

HasHistories特质添加到将被跟踪的模型。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Ferdiunal\History\HasHistories;

class Article extends Model
{
    use HasHistories;

    public function getModelLabel()
    {
        return $this->display_name;
    }
}

请记住,您需要实现特质中的抽象方法getModelLabel。这为历史提供了模型实例的名称。

获取模型的 历史

$model->histories();
//or dynamic property
$model->histories;

获取用户的操作

$user->operations();
//or dynamic property
$user->operations;

额外的查询条件

Both historiesoperations 返回 Eloquent 关联,也用作查询构建器。您可以通过链式条件添加更多约束。

// get the lastest 10 records
$model->histories()->orderBy('performed_at', 'desc')->take(10)

// filter by user id
$model->histories()->where('user_id', 10010)

历史记录

//get the associated model
$history->model();

//get the associated user
//the user is the authenticated user when the action is being performed
//it might be null if the history is performed unauthenticatedly
$history->user();
//check user existence
$history->hasUser();

//get the message
$history->message;

//get the meta(only available when it's an updating operation)
//the meta will be an array with the properties changing information
$history->meta;

//get the timestamp the action was performed at
$history->performed_at;

示例消息

Created Project my_project
   │       │         │
   │       │         └───── instance name(returned from `getModelLabel`)
   │       └─────────────── model name(class name or localized name)
   └─────────────────────── event name(default or localized name)

示例元数据

[
    ['key' => 'name', 'old' => 'myName', 'new' => 'myNewName'],
    ['key' => 'age', 'old' => 10, 'new' => 100],
    ...
]

自定义历史记录

除了内置的 created/updating/deleting/restoring 事件外,您还可以使用 ModelChanged 事件存储自定义历史记录。

use Ferdiunal\History\Events\ModelChanged;

...
//fire a model changed event
event(new ModelChanged($user, 'User roles updated', $user->roles()->pluck('id')->toArray()));

ModelChanged 构造函数接受两个/三个参数。第一个是与关联的模型实例;第二个是消息;第三个是可选的,即元数据(数组)。

本地化

您可以将模型类型名称本地化。

为此,请将语言行添加到已发布的语言文件中的 models 数组,其中键是 类的基名,以蛇形命名

示例语言配置

/*
|--------------------------------------------------------------------------
| Tracker Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used across application for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/

'created' => '创建:model:label',

'updating' => 'actualizar :model :label',

'deleting' => ':model :label löschen',

'restored' => ':model:labelを復元',

//you may added your own model name language line here
'models' => [
    'project' => '项目',
    'component_template' => '组件模板',
]

这将翻译您的模型历史记录为

创建项目project_001

过滤器

您可以在配置文件中设置白名单和黑名单。请遵循已发布的配置文件中的描述指南。

/*
|--------------------------------------------------------------
| Events whitelist
|--------------------------------------------------------------
|
| Events in this array will be recorded.
| Available events are: created, updating, deleting, restored
|
*/
'events_whitelist' => [
    'created', 'updating', 'deleting', 'restored',
],

/*
|--------------------------------------------------------------
| Attributes blacklist
|--------------------------------------------------------------
| 
| Please add the whole class names. Example: \App\User:class
| For each model, attributes in its respect array will NOT be recorded into meta when performing update operation.
|
*/
'attributes_blacklist' => [
    // \App\User::class => [
    //     'password'
    // ],
],

/*
|--------------------------------------------------------------
| User blacklist
|--------------------------------------------------------------
|
| Operations performed by users in this array will NOT be recorded.
| Please add the whole class names. Example: \App\User:class
| Use 'nobody' to bypass unauthenticated operations
|
*/
'user_blacklist' => [
    
],
/*
|--------------------------------------------------------------
| Enviroments blacklist
|--------------------------------------------------------------
|
| When application's environment is in the list, tracker will be disabled
|
*/
'env_blacklist' => [
    
],

身份验证守卫

如果您的用户正在使用非默认身份验证守卫,即使历史来源是由认证用户生成的,您可能会看到所有的 $history->hasUser() 都变成 false

为了解决这个问题,您需要在配置文件中启用自定义身份验证守卫扫描

/*
|--------------------------------------------------------------
| Enable auth guards scan
|--------------------------------------------------------------
|
| You only need to enable this if your users are using non-default auth guards.
| In that case, all tracked user operations will be anonymous.
|
| - Set to `true` to use a full scan mode: all auth guards will be checked. However this does not ensure guard priority.
| - Set to an array to scan only specific auth guards(in the given order). e.g. `['web', 'api', 'admin']`
|
*/
'auth_guards' => null

自定义元数据

您可以定义自己的元数据方法。默认情况下,对于 updating 事件,元数据由修改的键组成,对于其他事件,元数据是 null

只需重新定义特质中的方法 getModelMeta

示例

class Article extends Model
{
    // if you want to use default trait method, you need to redeclare it with a new name
    use HasHistories {
        getModelMeta as protected traitGetModelMeta;
    };

    ...
    
    public function getModelMeta($event)
    {
        // using defaults for updating
        if($event == 'updating') return $this->traitGetModelMeta($event);
        // passing full model to meta
        // ['key1' => 'value1', 'key2' => 'value2', ...]
        else return $this;
    }
}

已知问题

  1. 在更新模型时,如果其模型标签(从 getModelLabel 返回的属性)已被修改,则历史消息将使用其新属性,这可能与您的期望不符。
class Article extends Model
{
    use HasHistories;

    public function getModelLabel()
    {
        return $this->title;
    }
}
// original title is 'my title'
// modify title
$article->title = 'new title';
$article->save();
// the updating history message
// expect: Updating Article my title
// actual: Updating Article new title

解决方案

public function getModelLabel()
{
    return $this->getOriginal('title', $this->title);
}