chapdel/history

Laravel的Eloquent模型历史跟踪

1.1.0 2023-02-24 12:55 UTC

This package is auto-updated.

Last update: 2024-09-24 16:21:31 UTC


README

Test Status Test Status Coverage Status Total Downloads Latest Stable Version License

历史

Laravel的Eloquent模型历史跟踪(现在支持自动加载!)

安装

Composer

Laravel 6.x及更高版本

composer require panoscape/history

Laravel 5.6.x

composer require "panoscape/history:^1.0"

服务提供者和别名

仅适用于Laravel 5.6.x

无需版本2.0+,它将自动加载包发现

config/app.php

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

迁移

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

配置

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

本地化

php artisan vendor:publish --provider="Panoscape\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 Panoscape\History\HasOperations;

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

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Panoscape\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 Panoscape\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);
}