michaeljmeadows/has-histories 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

michaeljmeadows/has-histories

最新稳定版本:v2.0.0

Composer 安装命令:

composer require michaeljmeadows/has-histories

包简介

A simple trait to aid Eloquent model version history logging.

README 文档

README

A simple trait to aid Eloquent model version history logging.

Installation

You can install the package via composer:

composer require michaeljmeadows/has-histories

Usage

Add a migration to store your model histories. This should contain all the same fields as your main model table as well as a reference ID to the original model. Your model's history table can be named however your like, but the default convention would be models -> model_histories. We recommend modifying your migrations as shown in this modification of the Laravel Jetstream User migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    private array $tables = [
        'users',
        'user_histories',
    ];

    public function up(): void
    {
        foreach ($this->tables as $tableName) {
            Schema::create($tableName, function (Blueprint $table) use ($tableName) {
                $isHistoriesTable = str($tableName)->contains('histories');

                $table->id();
                if ($isHistoriesTable) {
                    $table->foreignId('user_id');
                }
                $table->string('name');
                $table->string('email');
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->foreignId('current_team_id')->nullable();
                $table->string('profile_photo_path', 2048)->nullable();
                $table->timestamps();

                if (! $isHistoriesTable) {
                    $table->unique('email');
                }
            });
        }
    }

    public function down(): void
    {
        foreach ($this->tables as $tableName) {
            Schema::dropIfExists($tableName);
        }
    }
};

Once the migration has been added, you can simply include the trait in your model's definition:

<?php

namespace App\Models;

use michaeljmeadows\Traits\HasHistories;
use Illuminate\Database\Eloquent\Model;

class NewModel extends Model
{
    use HasHistories;
	

Restoring Models

Models can be restored using one of three methods:

$newModel->restorePrevious();
$newModel->restorePreviousIteration(3);
$newModel->restoreBeforeDate('2022-01-01');

These functions return true on success and false if a historic state was not found.

restorePrevious() will restore a model to its previous state in the histories table.

restorePreviousIteration(int $index) will restore a model to a state using zero-based numbering. (i.e. restorePreviousIteration(0) is the same as restorePrevious()).

restoreBeforeDate(DateTimeInterface|string $date) will restore a model to the most recent state before the given $date value using the updated_at and created_at fields.

Restoration Notes

  • When restored, a copy of the current model is also saved to the histories table.
  • HasHistories uses the history table id field to assess the most recent state, as multiple restorations can lead to apparent duplicates appearing in the histories table.

Customising Behaviour

Ignored Fields

Not every change to a model's attributes is worth logging. In the Jetstream User example above, it may be that you'd rather ignore changes to email_verified_at. In this case, you can add a protected array attribute $ignoredFields to your model specifying which attributes you're not interested in:

<?php

namespace App\Models;

use michaeljmeadows\Traits\HasHistories;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasHistories;
	
    protected array $ignoredFields = [
        'email_verified_at',
    ];

If you choose to ignore fields these should not be included in the history table migration.

Histories Table Name

By default, HasHistories uses the naming convention models -> model_histories when determining the history table name, but if for whatever reason that doesn't work for you, you can specify a different history table name by adding a protected string attribute $historiesTable to your model:

<?php

namespace App\Models;

use michaeljmeadows\Traits\HasHistories;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasHistories;
	
    protected string $historyTable = 'user_logging'; // Instead of 'user_histories'.

Histories Table Model Reference

By default, HasHistories associates an entry in the history table with a model with an attribute in the form models -> model_id, but if for whatever reason that doesn't work for you, you can specify a different field by adding a protected string attribute $historiesModelIdReference:

<?php

namespace App\Models;

use michaeljmeadows\Traits\HasHistories;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasHistories;
	
    protected string $historiesModelIdReference = 'user_model_id'; // Instead of 'user_id'.

Histories Table Connection

By default, HasHistories expects that the history table will use the same connection as the model to which it is applied. Occasionally you may want to specify a different connection for your history table. This can be done with an optional parameter in your saveHistory method call:

<?php

namespace App\Observers;

use App\Models\NewModel;
use Illuminate\Support\Facades\Auth;

class NewModelObserver
{
    public function creating(NewModel $newModel): void
    {
        $newModel->saveHistory('sqlite');
    }

When restoring models, the same connection parameter can be added at the end of each method call:

$newModel->restorePrevious('sqlite');
$newModel->restorePreviousIteration(3, 'sqlite');
$newModel->restoreBeforeDate('2022-01-01', 'sqlite');

michaeljmeadows/has-histories 适用场景与选型建议

michaeljmeadows/has-histories 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 23 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 11 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 michaeljmeadows/has-histories 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 michaeljmeadows/has-histories 我们能提供哪些服务?
定制开发 / 二次开发

基于 michaeljmeadows/has-histories 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 23
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 13
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-11-08