Laravel Hashid 整合了 [Base62], [Base64], [Hashids], [Optimus] 等高性能编码算法,并提供了统一的、优雅的、简单易用的调用接口,将「敏感数据」混淆(编码)成可还原的、非连续的、URL 安全的标识符 (ID) 。php
项目主页及详细文档: https://github.com/ElfSundae/...laravel
新包求 Star 求反馈 git
$ composer require elfsundae/laravel-hashid
对于 Lumen 或 Laravel 低于 5.5 版本,须要手动注册 service provider:github
ElfSundae\Laravel\Hashid\HashidServiceProvider::class
发布配置文件:算法
# For Laravel application: $ php artisan vendor:publish --tag=hashid # For Lumen application: $ cp vendor/elfsundae/laravel-hashid/config/hashid.php config/hashid.php
Hashid 的配置文件和 Laravel 框架的众多管理 (manager) 服务的配置极其相似,例如数据库、缓存、队列等。因此无需花费额外时间来学习如何配置它。数据库
咱们来看个例子:缓存
'default' => 'id', 'connections' => [ 'basic' => [ 'driver' => 'base64', ], 'hashids' => [ 'driver' => 'hashids', 'salt' => 'sweet girl', ], 'id' => [ 'driver' => 'hashids_integer', 'salt' => 'My Application', 'min_length' => 6, 'alphabet' => '1234567890abcdef', ], 'base62' => [ 'driver' => 'base62', 'characters' => 'f9FkqDbzmn0QRru7PBVeGl5pU28LgIvYwSydK41sCO3htaicjZoWAJNxH6EMTX', ], ],
hashid()
全局函数获取 connection 或 driver 实例。hashid_encode()
全局函数进行编码。hashid_decode()
全局函数进行解码。示例:安全
hashid_encode(123456); // "xkNDJ" hashid_decode('xkNDJ'); // 123456 hashid_encode(123456, 'optimus'); // 1101845824 hashid_decode(1101845824, 'optimus'); // 123456 hashid_encode(123456, 'base62'); // "W7E" hashid_encode('123456', 'base62'); // "FMJUCzH4" hashid_decode('W7E', 'base62_integer'); // 123456
base62
, base62_integer
base64
, base64_integer
hashids
, hashids_hex
, hashids_integer
, hashids_string
hex
, hex_integer
optimus
hashid:alphabet
:生成随机串 0-9a-zA-Z
hashid:optimus
:生成 [Optimus] 编码要用到的参数要使用本身的编解码算法,只须要建立一个类实现 ElfSundae\Laravel\Hashid\DriverInterface
接口便可,这个接口只有两个方法: encode
和 decode
。初始化方法可选接收一个名为 $config
的配置参数,同时也支持类型提示式依赖注入。app
例如:composer
<?php namespace App\Hashid; use ElfSundae\Laravel\Hashid\DriverInterface; use Illuminate\Contracts\Encryption\Encrypter; class CustomDriver implements DriverInterface { protected $encrypter; protected $serialize; public function __construct(Encrypter $encrypter, array $config = []) { $this->encrypter = $encrypter; $this->serialize = $config['serialize'] ?? false; } public function encode($data) { return $this->encrypter->encrypt($data, $this->serialize); } public function decode($data) { return $this->encrypter->decrypt($data, $this->serialize); } }
要使用这个自定义驱动,在配置文件中指定它便可:
'connections' => [ 'custom' => [ 'driver' => App\Hashid\CustomDriver::class, 'serialize' => false, ], // ... ]
调用示例:
hashid_encode(123456, 'custom');
若是想为自定义驱动使用一个短名字,注册一个容器绑定便可:
$this->app->bind('hashid.driver.custom', CustomDriver::class);
更多使用方法请参考项目主页:https://github.com/ElfSundae/...