shikachuu / laravel-cuid2
为您的 Laravel 应用提供一流的 CUID2 支持
1.0.0
2023-11-26 20:55 UTC
Requires
- php: ^8.1
- illuminate/support: ^v10
- visus/cuid2: ^4.0
Requires (Dev)
- doctrine/dbal: ^3.7
- laravel/pint: ^1.13
- orchestra/testbench: ^8.13
- pestphp/pest: ^2.23
- pestphp/pest-plugin-laravel: ^2.2
README
为您的 Laravel 应用提供缺失的 CUID2 实现。
安全、防碰撞的 ID,基本上是下一代 UUID。
安装
您可以通过 composer
安装此包
composer require shikachuu/laravel-cuid2
您可以使用以下命令发布配置文件
php artisan vendor:publish --provider="Shikachuu\LaravelCuid2\Cuid2ServiceProvider"
配置文件将发布在 config/cuid2.php
中,在此文件中,您可以更改默认的 key-length
,默认设置为 24
。
使用
通过 Facade 或辅助函数的基本使用
这是在 Laravel 应用中创建新 CUID2 的最简单方式。
您可以使用提供的 facades 和辅助函数
$id = cuid2(); // or provide an argument with the key size $id = cuid2(30); // or call the facade directly $idFromTheFacade = \Shikachuu\LaravelCuid2\Facades\Cuid2::generate(30);
现在让我们验证上面的示例
\Shikachuu\LaravelCuid2\Facades\Cuid2::validate($id);
验证
您可以使用提供的 cuid2
验证规则在默认的 Laravel 验证器 中
Validator::validate(['cuid' => 'qo08kg4ogogcc4sowwskkwko'], ['cuid' => 'cuid2']);
迁移
您可以在迁移中使用 cuid2
和 foreignCuid2
作为字段类型
<?php declare(strict_types=1); use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class () extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('tests', function (Blueprint $table): void { $table->cuid2()->primary(); // generates a `cuid2` filed to use it as the primary key }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('tests'); } };
默认情况下,这些规则将创建一个名为 cuid2
的字段,但您可以通过明确指定列名来自定义此行为
$table->cuid2('myFieldName');
模型
就像 UUID 一样,您也可以在模型中使用 CUID2 来在查询中自动生成和验证 ID
<?php declare(strict_types=1); namespace Workbench\App\Models; use Illuminate\Database\Eloquent\Model; use Shikachuu\LaravelCuid2\Eloquent\Concerns\HasCuid2; class Orders extends Model { use HasCuid2; protected $primaryKey = 'cuid2'; }
许可证
MIT 许可证 (MIT)。有关更多信息,请参阅 LICENSE。
贡献
以下是一些贡献指南
- 如果您想为代码库做出贡献,请提出一个问题以提出更改或功能建议。
- 不要将功能更改或修复与重构混合使用 - 这会使代码难以审查,并意味着维护者(时间有限)需要做更多测试。
- 不要为拼写错误提出 PR,这些是不必要的 - 只需提出一个问题。
- 请始终提供您更改的内容、如何进行更改以及如何测试更改的总结。
- 我们通常希望每个 PR 中只有一个提交,如果您有更多,那么您应该有一个完美的理由。
- 所有提交都必须有
Signed-off-by:
行,并符合开发者证书来源。 - 所有更改都必须通过
composer lint
进行代码检查,并且必须通过旧的和新的测试。
要测试您的更改,请使用包含的 composer test
命令,请始终使用适当的测试用例覆盖您的更改,当可能时,首选 table tests。
示例文件总是欢迎添加到工作目录文件夹中。请随时提供您修复/功能的示例用例。
此存储库中的所有测试和代码都应能够在使用 OCI 运行时的原始 php:8.2-cli-alpine
容器中运行。(在我的情况下:podman run --rm -it -v $PWD:/app:Z -w /app php:8.2-cli-alpine ash
)这可能在未来被 devcontainers 或 bake 文件 替换。