deligoez/laravel-model-hashid

为 Laravel Eloquent 模型生成、保存和路由 Stripe/Youtube 类似的 Hash ID

v3.0.0 2024-07-23 13:32 UTC

README

Latest Version on Packagist Total Downloads Packagist
Maintainability Rating Reliability Rating Security Rating
Coverage Lines of Code Bugs
Technical Debt Vulnerabilities Code Smells Duplicated Lines (%)
tests code style types Quality Gate Status
Open Source Love

使用此包,您可以为您 Eloquent 模型生成、保存和路由 类似 Stripe 的 Hash Id。

Hash Id 短小、唯一、非连续,可以为 URL 生成唯一 Id 并隐藏数据库行号。有关 Hash Id 的更多信息,请访问 hashids.org

使用此包,您可以自定义 Hash Id 生成并添加模型前缀和分隔符。

对于 id 为 1234User 模型,您可以生成如 user_kqYZeLgo 的 Hash Id。

因此,而不是; https://your-endpoint.com/user/1234

您可以拥有这样的端点;
https://your-endpoint.com/user/user_kqYZeLgo

您完全控制 Hash Id 的长度和样式。查看配置文件以获取更多选项。

目录

功能

  • 可定制的 Hash Id 生成
    • Hash Id 盐
    • 长度
    • HashID 字母表
    • 模型前缀长度和大小写
    • 分隔符
  • 特定于模型的 Hash Id 生成
    • 每个模型的用户定义前缀(可选)
    • 为每个模型定义单独的配置
  • 使用 Hash Id 进行路由(模型)绑定(可选)
  • 自动将 Hash Id 保存到数据库中(可选)

兼容性表

下表显示了 Laravel、PHP 和本包 当前版本 的兼容性。

安装

  1. 通过 Composer 安装
    composer require deligoez/laravel-model-hashid
  2. 发布配置文件
    php artisan vendor:publish --provider="Deligoez\LaravelModelHashId\LaravelModelHashIdServiceProvider" --tag="config"

使用

模型 Hash Id 生成

HasHashId 特性添加到任何应使用 Hash Id 的 Laravel 模型。

use Illuminate\Database\Eloquent\Model;
use Deligoez\LaravelModelHashId\Traits\HasHashId;

class ModelA extends Model
{
    use HasHashId;
    
    ...
}

模型属性和静态模型函数

您可以使用 hashIdhashIdRaw 属性以及 keyFromHashId() 静态模型函数。

$modelA = ModelA::find(1234);
$modelA->hashId;    // model_a_kqYZeLgo
$modelA->hashIdRaw; // kqYZeLgo

ModelA::keyFromHashId('model_a_kqYZeLgo') // 1234

查询构建器函数

您可以使用所有与 Hash Id 相关的 Laravel 查询构建器函数。

// Find a model by its Hash Id.
ModelA::findByHashId('model_a_kqYZeLgo');

// Find multiple models by their Hash Ids.
ModelA::findManyByHashId(['model_a_kqYZeLgo', 'model_a_ZeLgokqY']);

// Find a model by its Hash Id or throw an exception.
ModelA::findOrFailByHashId('model_a_kqYZeLgo');

// Find a model by its Hash Id or or call a callback.
ModelA::findOrByHashId('model_a_kqYZeLgo');

// Find a model by its Hash Id or return fresh model instance.
ModelA::findOrNewByHashId('model_a_kqYZeLgo');

// Add a where clause on the Hash Id to the query.
ModelA::whereHashId('model_a_kqYZeLgo');

// Add a where not clause on the Hash Id to the query.
ModelA::whereHashIdNot('model_a_kqYZeLgo');

路由和路由模型绑定(可选)

只需将 HasHashIdRouting 特性添加到您想使用 Hash Id 路由的模型。

use Illuminate\Database\Eloquent\Model;
use Deligoez\LaravelModelHashId\Traits\HasHashIdRouting;

class ModelA extends Model
{
    use HasHashIdRouting;
    
    ...
}

路由模型绑定(隐式)

您可以通过 Laravel 习惯用法定义一个类似于这样的路由和/或控制器方法。

// You can call this route with a Hash Id: your-endpoint.com/model-a/model_a_kqYZeLgo
Route::get('/model-a/{modelA}', function (ModelA $modelA) {
    // Your ModelA instance
    $modelA;
});

路由模型绑定(显式)

您也可以在 RouteServiceProvider 上定义自定义模型键。

Route::model('hash_id', ModelA::class);
// You can call this route with a Hash Id: your-endpoint.com/model-a/model_a_kqYZeLgo
Route::get('/model-a/{hash_id}', function ($modelBinding) {
    // Your ModelA instance
    $modelBinding;
});

将 Hash Id 保存到数据库中(可选)

您可以将 SavesHashId 特性添加到任何应保存生成 Hash Id 的 Laravel 模型。

之后,您应在配置文件中设置 database_column 设置。您可以为每个模型单独定义 database_column 设置,也可以为您的所有模型定义。

use Illuminate\Database\Eloquent\Model;
use Deligoez\LaravelModelHashId\Traits\SavesHashId;

class ModelA extends Model
{
    use SavesHashId;
    
    ...
}

所有 Hash Id 生成或解码方法都是即时工作的。因此,您不需要将 Hash Id 保存到数据库中,这就是原因。

由于生成 Hash Id 需要整数模型 id/key,请记住将 Hash Id 存储到数据库中将导致额外的数据库查询。

Hash Id 术语

典型的 Hash Id 由 3 部分组成。

  • 模型前缀(model_a
  • 分隔符(_
  • 原始 Hash Id(kqYZeLgo

模型前缀和分隔符是可选的。您可以生成仅包含原始哈希ID的哈希ID。

配置

这是已发布配置文件的内容

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Salt String
    |--------------------------------------------------------------------------
    |
    | This salt string is used for generating HashIDs and should be set
    | to a random string, otherwise these generated HashIDs will not be
    | safe. Please do this definitely before deploying your application!
    |
    */

    'salt' => env('HASHID_SALT', 'your-secret-salt-string'),

    /*
    |--------------------------------------------------------------------------
    | Raw HashID Length
    |--------------------------------------------------------------------------
    |
    | This is the length of the raw HashID. The model prefix, separator
    | and the raw HashID are combined all together. So the Model HashID
    | length is the sum of raw HashID, separator, and model prefix lengths.
    |
    | Default: 13
    |
    */

    'length' => 13,

    /*
    |--------------------------------------------------------------------------
    | HashID Alphabet
    |--------------------------------------------------------------------------
    |
    | This alphabet will generate raw HashIDs. Please keep in mind that it
    | must contain at least 16 unique characters and can't contain spaces.
    |
    | Default: 'abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ234567890'
    |
    */

    'alphabet' => 'abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ234567890',

    /*
    |--------------------------------------------------------------------------
    | Model Prefix Length
    |--------------------------------------------------------------------------
    |
    | Here you can specify the length of the model prefix. By default, they
    | will generate it from the first letters of short class name.
    | Set it -1 to use full short class name as prefix.
    | Set it 0 to not use any prefix at all.
    |
    | Default: 3
    |
    */

    'prefix_length' => 3,

    /*
    |--------------------------------------------------------------------------
    | Model Prefix Case
    |--------------------------------------------------------------------------
    |
    | Here you can set the case of the prefix. Please keep in mind that for
    | some prefix cases, underscore (‘_’) characters will be added to the
    | prefix if your model name is multi word.
    |
    | Default: 'lower'
    |
    | Supported: "lower", "upper", "camel", "snake", "kebab",
    |            "title", "studly", "plural_studly"
    |
    */

    'prefix_case' => 'lower',

    /*
    |--------------------------------------------------------------------------
    | HashID Model Prefix Separator
    |--------------------------------------------------------------------------
    |
    | Here you can set the separator for your HashIDs. The separator
    | will be added between model prefix and the raw HashID.
    |
    | Default: '_'
    |
    */

    'separator' => '_',

    /*
    |--------------------------------------------------------------------------
    | HashID Database Column
    |--------------------------------------------------------------------------
    |
    | By using `SavesHashIDs` trait, you can save model HashIDs to database.
    | Here you can set the database column name for HashIDs to save.
    |
    | Default: 'hash_id'
    |
    */

    'database_column' => 'hash_id',

    /*
    |--------------------------------------------------------------------------
    | Model Specific Generators
    |--------------------------------------------------------------------------
    |
    | Here you can set specific HashID generators for individual Models.
    | Each one of the setting above can be defined per model. You can
    | see an example below as a comment.
    |
    */

    'model_generators' => [
        // App\Models\User::class => [
        //     'salt'            => 'your-model-specific-salt-string',
        //     'length'          => 13,
        //     'alphabet'        => 'abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ234567890',
        //     'prefix_length'   => 3,
        //     'prefix_case'     => 'lower',
        //     'separator'       => '_',
        //     'database_column' => 'hash_id',
        // ],

        // App\Models\Post::class => [
        //     'salt'            => 'your-model-specific-salt-string',
        //     'length'          => 13,
        //     'alphabet'        => 'abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ234567890', 
        //     'prefix'          => 'abc', // Custom prefix that is not auto-generated
        //     'separator'       => '_',
        // ],
    ],
];

路线图

  • 自定义模型前缀(非由模型名称生成)(感谢@plunkettscott)
  • 哈希ID验证规则
  • 通用生成器(未绑定到Laravel模型)

测试

composer test

已使用

以下公司/产品使用此项目,您也可以添加您的公司

变更日志

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

贡献

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

安全漏洞

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

鸣谢

许可证

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