jetcod/eloquent-keygen
一个提供与Eloquent模型无缝集成的Snowflake ID生成的Laravel包
v1.1.0
2024-07-18 12:17 UTC
Requires
- php: ^7.4|^8.0
- godruoyi/php-snowflake: ^2.0|^3.0
Requires (Dev)
- fakerphp/faker: ^1.23
- friendsofphp/php-cs-fixer: ^3.49
- orchestra/testbench: ^6.0|^7.0|^8.0|^9.0
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^9.0|^10.0|^11.0
This package is not auto-updated.
Last update: 2024-09-26 13:20:18 UTC
README
这是一个为Laravel Eloquent模型提供Snowflake ID生成无缝集成的Laravel包。通过使用高度分布式的唯一标识符系统来自动生成主键,简化主键管理。使用这个易于使用的包来提高您应用程序的可扩展性和效率。
安装
要安装 jetcod/deloquent-keygen
,您可以使用Composer,PHP的依赖管理器。在终端中运行以下命令
composer require jetcod/eloquent-keygen
然后您需要发布配置文件
php artisan vendor:publish --provider="eloquent-key-generator-config"
如何使用?
要使用此包,请按照以下步骤操作
- 扩展您的模型:
在您的Eloquent模型中,扩展Jetcod\Eloquent\Model而不是扩展Illuminate\Database\Eloquent\Model。这将启用使用Snowflake算法自动生成ID。
<?php namespace App\Models; use Jetcod\Eloquent\Model as EloquentModel; class YourModel extends EloquentModel { // Your model code here }
- 使用Trait:
如果您不想扩展Eloquent模型,或者只想将Snowflake ID生成应用于一个模型,您可以在模型类中使用Snowflake trait。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model as EloquentModel; use Jetcod\Eloquent\Traits\Snowflake; class YourModel extends EloquentModel { use Snowflake; }
- 禁用特定模型的Snowflake生成:
如果您想禁用特定模型的Snowflake ID生成,您可以在该模型中添加一个返回false的snowflake方法。
<?php namespace App\Models; use Jetcod\Eloquent\Model as EloquentModel; class AnotherModel extends EloquentModel { protected function snowflake(): bool { return false; } // Your model code here }
该snowflake方法返回一个布尔值,表示是否为该模型启用或禁用Snowflake ID生成。
- 分布式系统的配置:
该包使用以下配置来生成分布式唯一标识符
<?php use Godruoyi\Snowflake\LaravelSequenceResolver; return [ 'attributes' => [ /* |------------------------------------------------------------------ | This represents the datacenter id used to generate snowflake ids. |------------------------------------------------------------------ */ 'datacenter' => env('SNOWFLAKE_DATACENTER_ID', 1), /* |-------------------------------------------------------------- | This represents the worker id used to generate snowflake ids. |-------------------------------------------------------------- */ 'worker' => env('SNOWFLAKE_WORKER_ID', 1), /* |-------------------------------------------------------------------------------------------------------- | This represents the sequence resolver class. It is to ensure that sequence-number generated in the same | millisecond of the same node is unique. | | Avaialable resolvers: | 1. Godruoyi\Snowflake\RandomSequenceResolver | 2. Godruoyi\Snowflake\FileLockResolver | 3. Godruoyi\Snowflake\LaravelSequenceResolver |-------------------------------------------------------------------------------------------------------- */ 'sequence_resolver' => env('SNOWFLAKE_SEQUENCE_RESOLVER', LaravelSequenceResolver::class), 'file_lock_directory' => env('SNOWFLAKE_File_LOCK_DIRECTORY', null), // Default is null, means use <app_path>/storage/snowflake directory. ], ];
许可证
本项目采用MIT许可证 - 请参阅LICENSE文件以获取详细信息。