Jim_Chen 2018-08-31 19:36:16 3433次浏览 0条评论 0 0 0

Github

JimChenWYU/yii2-hashids

安装

composer require jimchen/yii2-hashids

使用

return [
    //...
    'components' => [
        //...
        'hashids' => [
            'class' => 'jimchen\hashids\HashidsComponent',
            'salt' => 'default channel salt',
            'length' => 'default channel length of the encode string',
            // 'default' => 'main' // default channel
            // 'connections' => null // other channel
        ],
    ],
];

关于 connections 配置

[
    ...
    'connections' => [
        'channel name' => [
            'salt' => 'the salt',
            'length' => 'the length of the encode string',
        ],
        ...
    ]
]

在你的代码中使用

use Yii;

$encode = Yii::$app->hashids->encode(12345);

var_dump(Yii::$app->hashids->decode($encode)); // [12345]

如何使用不同的盐值,通过频道区分

use Yii;

$otherChannelHashids = \Yii::createObject('hashids.manager')->connection('channel name');

$encode = $otherChannelHashids->encode(12345);

var_dump($otherChannelHashids->decode($encode)); // [12345]

需要注意

  1. 因为底层Hash算法是使用 hashids/hashids, 那么根据其 API 每次 decode 均返回一个数组,如果有需要只返回一个数需要自行处理,为什么它会这么设计?这是因为 encode 其实不单单可以 encode 一个数,还可以是一个一维数字数组。

  2. 只能对整形数字进行 encode

  3. 可能你很好奇使用场景在哪里,我们设想一下我们的网站 URL 设计成 RESTFUL 风格时,是不是有时会暴露了用户ID的值,而且很多时候是直接采用数据库的自增实现,那么别人就很容易通过 ID 猜测我们网站的用户量,此时 hashids 作用就可以把这些ID进行隐藏起来。

    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册