mvaliolahi / smart-hash
Laravel Smart Hash 模型 ID 和请求。
v0.0.17
2024-02-28 12:16 UTC
Requires
- hashids/hashids: ^4.1
Requires (Dev)
- laravel/framework: ^8.0
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.0
README
什么是 hashids?
Hashids 是一个小型的开源库,可以从数字生成短、唯一、非顺序的 ID。它将数字如 347 转换为字符串如“yr8”,或将数字数组如[27, 986]转换为“3kTMd”。
更多信息请访问 hashids.org。
为什么我们应该使用这个库?
您的客户端处理哈希 ID,但每次您的应用程序接收到 id
或 ids
请求时,SmartHash 会为您解码。
- 易于使用!
- 隐藏数据库 ID 给客户端。
- 自动对前端编码模型 ID,对后端解码(解码来自参数或请求体的所有
id
或ids
请求) - 不需要像
findByHashid
这样的方法
安装
$ composer require mvaliolahi/smart-hash $ php artisan vendor:publish
如何使用
- 在您的模型中使用
SmartHash
特性。
class Category extends Model { use SmartHash; } $category->hashId()
使用 SmartHash 特性后,Category::first()->id 将返回 jR
而不是 1
,您可以通过 $category->id() 方法访问原始 ID。
- 在 AppServiceProvider 的 boot 方法中定义您的模型,因为
路由模型绑定
$this->app->singleton('smart-hash', function() { return [ 'category' => Category::class, 'user' => User::class, ]; });
向解码查找表中添加新参数
编辑 config/smart-hash.php
文件,下一步很明显!例如,如果我们想自动解码 id
、category_id
和数组参数如 ids
,配置如下。
<?php return [ 'single_parameters' => [ 'id', 'category_id' ], 'array_parameters' => [ 'ids', ] ];
手动查找
$post = Post::findByHash('vm'); $post = Post::findOrFailByHash('vm');