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/...