lemaur/laravel-human-id

为您的模型自动生成人类ID。

1.1.0 2023-10-18 18:18 UTC

README

Latest Version on Packagist Total Downloads License Tests GitHub Sponsors Trees

本包受到了文章“为人类设计API:对象ID”的启发
该文章发表于Dev(2022年8月30日 / 作者:Paul Asjes)。

我非常喜欢Stripe定义对象ID的方法,所以我尝试为Laravel实现类似的功能。
基本上,该包通过在ULID前添加前缀并在它们之间添加分隔符来生成所谓的“人类ID”。

一个好的例子胜过千言万语...

👇 the structure -----------------

{prefix}{separator}{ulid}


👇 the params --------------------

prefix: post
separator: _
ulid: 26 alphanumeric characters


👇 the result --------------------

post_01h554vp2prg6zfayagh83ccx7

支持我

大家好,

你们喜欢这个包吗?你们觉得它有用,并且适合你们的项目吗?

我很高兴能帮到你们,如果你们考虑支持我的工作,我将不胜感激。

你们甚至可以选择 😃


安装

您可以通过Composer安装此包

composer require lemaur/laravel-human-id

用法

  1. 在您的迁移文件中添加“人类ID”字段。
  2. Lemaur\HumanId\Concerns\HasHuids特质导入到您的Eloquent模型中。

以下是一个在模型上实现特质的真实示例。

// database\migrations\create_posts_table.php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', static function (Blueprint $table) {
            $table->id();
            
            $table->huid(); // <-- declare "huid" field
            
            // other fields...
        });
    }
}
// app\Models\Post.php

namespace App\Models;

use \Illuminate\Database\Eloquent\Model;
use \Lemaur\HumanId\Concerns\HasHuids;

class Post extends Model
{
    use HasHuids; // <-- import trait
    
    /** @var string */
    private const HUID_PREFIX = 'post'; // <-- declare prefix (max 4 characters)
}

// this will generate a huid like --> post_01h554vp2prg6zfayagh83ccx7

配置

您可以为字段使用不同的名称(当前是huid)和不同的分隔符(当前是_)。
要这样做,您应该发布配置文件(config/human-id.php)并从中更改它们。

php artisan vendor:publish --tag=human-id-config

测试

composer test

变更日志

请参阅变更日志以获取有关最近更改的更多信息。

贡献

请参阅贡献指南以获取详细信息。

安全漏洞

请查看我们的安全策略,了解如何报告安全漏洞。

鸣谢

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。