tailflow/laravel-human-readable-keys

为 Eloquent 模型生成类似 Stripe 的 ID

1.0 2021-02-04 08:24 UTC

This package is auto-updated.

Last update: 2024-09-19 19:48:10 UTC


README

Latest Version on Packagist Build Status on Github Actions

您是否曾想为 Eloquent 模型生成类似 Stripe 的 ID?此包正是为此目的而设计!

安装

您可以通过 composer 安装此包

composer require tailflow/laravel-human-readable-keys

使用

  1. 在迁移中将 id(或您的主键列)的类型更改为 string
Schema::create('users', function (Blueprint $table) {
    $table->string('id');
    
    ...
});
  1. HasHumanReadableKey 特性添加到模型中
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Tailflow\HumanReadableKeys\Concerns\HasHumanReadableKey;

class User extends Model
{
    use HasHumanReadableKey;

   ...
}
  1. (可选)自定义键前缀和长度

默认情况下,使用表的单数形式作为生成键的前缀。您可以通过在模型上覆盖 getKeyPrefix 方法来自定义它

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Tailflow\HumanReadableKeys\Concerns\HasHumanReadableKey;

class User extends Model
{
    use HasHumanReadableKey;

   ...
   
    public function getKeyPrefix(): string
    {
        return 'account';
    }
}

生成的键包含一个独特的哈希,长度为 24 个字符。要自定义哈希长度,覆盖 getKeyLength 方法

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Tailflow\HumanReadableKeys\Concerns\HasHumanReadableKey;

class User extends Model
{
    use HasHumanReadableKey;

   ...
   
    public function getKeyLength(): string
    {
        return 16;
    }
}

许可证

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