abe / laravel-prism
New Laravel project setup.
Fund package maintenance!
abe
Requires
- php: ^8.3|^8.4
- godruoyi/php-snowflake: ^3.1
- illuminate/contracts: ^10.0||^11.0||^12.0
- jiannei/laravel-response: ^6.0
- laravel/prompts: ^0.1.18|^0.2.0|^0.3.0
- spatie/laravel-package-tools: ^1.19
Requires (Dev)
- larastan/larastan: ^2.6.5||^3.0
- laravel/pint: ^1.0
- nunomaduro/collision: ^7.8|^8.0
- orchestra/testbench: ^8.0||^9.0||^10.0
- pestphp/pest: ^2.0||^3.0
- pestphp/pest-plugin-arch: ^2.0||^3.0
- pestphp/pest-plugin-laravel: ^2.0||^3.0
- phpstan/extension-installer: ^1.0
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
README
New Laravel project setup.
Installation
You can install the package via composer:
composer require abe/laravel-prism
功能
雪花ID (Snowflake ID)
使用 HasSnowflake
trait 可以让你的模型在创建时自动生成并填充雪花ID。
使用方法
- 在模型中引入 trait
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Abe\Prism\Traits\HasSnowflake; class Product extends Model { use HasSnowflake; /** * 需要自动生成雪花ID的字段列表 * 如果不设置,默认使用模型主键 */ protected $snowflakeColumns = ['id', 'another_snowflake_field']; }
- 创建模型时会自动生成雪花ID
$product = new Product(); $product->name = '测试产品'; $product->save();
前后端雪花ID处理
由于 JavaScript 对大整数的限制(最大安全整数为 2^53-1),雪花ID在前端可能会出现精度丢失问题。HasSnowflake
trait 自动处理了这一问题:
- 自动将雪花ID字段添加到模型的
$casts
数组,确保在 JSON 序列化时转为字符串
前端处理示例(使用 JavaScript):
// 显示ID时保持字符串形式 console.log("产品ID: " + product.id); // 不要进行数值运算 // 提交时直接发送字符串形式的ID axios.post('/api/products', { id: productId, // 已经是字符串形式,不需要转换 // 其他字段... });
这种方式确保雪花 ID 在前后端传递过程中不会丢失精度。
注意事项
- 本功能基于 godruoyi/php-snowflake 包实现
- 确保你的数据库字段类型足够大以存储雪花 ID(推荐使用 BIGINT UNSIGNED)
- 雪花ID生成器配置在 PrismServiceProvider 中注册,可根据需要调整起始时间等参数
响应处理 (HasResponse)
使用 HasResponse
trait 可以让你的控制器方法返回统一格式的响应。
使用方法
- 在控制器中引入 trait
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Abe\Prism\Traits\HasResponse; class ProductController extends Controller { use HasResponse; public function show($id) { $product = Product::find($id); if (!$product) { return $this->fail('Product not found', 404); } return $this->fail($product); } }
- 使用
success
和fail
方法返回响应
public function store(Request $request) { $product = Product::create($request->all()); return $this->success($product, 'Product created successfully', 201); }
注意事项
HasResponse
trait 提供了success
和fail
方法,分别用于返回成功和错误的响应
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.