PHPackages                             bestyii/yii2-snowflake - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. bestyii/yii2-snowflake

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

bestyii/yii2-snowflake
======================

Snowflake for Yii2

v1.0.0(3y ago)3886BSD-3-ClausePHP

Since Aug 20Pushed 3y ago1 watchersCompare

[ Source](https://github.com/bestyii/yii2-snowflake)[ Packagist](https://packagist.org/packages/bestyii/yii2-snowflake)[ RSS](/packages/bestyii-yii2-snowflake/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

YII2 Snowflake 雪花算法ID生成器
========================

[](#yii2-snowflake-雪花算法id生成器)

[![snowflake](snowflake.png)](snowflake.png)

雪花算法ID生成器 (Yii2 组件)

[![Latest Stable Version](https://camo.githubusercontent.com/0914dcd2f25996a83b3202200dde1ccac33b181884a82519dff419bd6f2b1085/68747470733a2f2f706f7365722e707567782e6f72672f626573747969692f796969322d736e6f77666c616b652f762f737461626c65)](https://packagist.org/packages/bestyii/yii2-snowflake)[![Total Downloads](https://camo.githubusercontent.com/1b6c2e610d0746491fce521300650fae75b01ceae8dff7713039081e9b417697/68747470733a2f2f706f7365722e707567782e6f72672f626573747969692f796969322d736e6f77666c616b652f646f776e6c6f616473)](https://packagist.org/packages/bestyii/yii2-snowflake)[![License](https://camo.githubusercontent.com/aadc1ced2a4f1c34b348b88ae100b84cea35e637d7e98d6a5c62c602d30e0e49/68747470733a2f2f706f7365722e707567782e6f72672f626573747969692f796969322d736e6f77666c616b652f6c6963656e7365)](https://packagist.org/packages/bestyii/yii2-snowflake)

环境要求
----

[](#环境要求)

PHP &gt;= 7.0

安装
--

[](#安装)

安装此扩展的首选方法是：[composer](http://getcomposer.org/download/).

项目根目录下运行

```
php composer.phar require --prefer-dist bestyii/yii2-snowflake "*"

```

或添加到`composer.json`文件的require区域中.

```
"bestyii/yii2-snowflake": "*"

```

### 配置

[](#配置)

#### 快速上手

[](#快速上手)

在配置文件中加入

```
return [
    //...
    'components' => [
        //...
        'snowflake' => [
            'class' => 'bestyii\snowflake\Snowflake',
            'startDate' => '2022-12-31',
        ],
    ],
];
```

参数说明startDate起始日期 , 字符串`Y-m-d`格式, 如: '2022-12-31'#### 高级配置

[](#高级配置)

雪花算法生成的 ID 并不能保证唯一，如当两个不同请求同一时刻进入相同的数据中心的相同节点时，而此时该节点生成的 sequence 又是相同时，就会导致生成的 ID 重复。 所以要想使用雪花算法生成唯一的 ID，就需要保证同一节点同一毫秒内生成的序列号是唯一的。

此扩展内置了基于redis的序列号生成器`\bestyii\snowflake\RedisSequenceResolver`,保证同一毫秒生成的序列号不同。

```
return [
    //...
    'components' => [
        //...
        'snowflake' => [
            'class' => 'bestyii\snowflake\Snowflake',
            'startDate' => '1970-1-1',
            'datacenterId' => 11,
            'workerId' => 22,
            'sequencer' =>  '\bestyii\snowflake\RedisSequenceResolver',
        ],
    ],
];
```

参数说明startDate起始日期datacenterId数据中心idworkerId主机idsequencer`\bestyii\snowflake\RedisSequenceResolver`, 需要配置 [yii2-redis](https://github.com/yiisoft/yii2-redis) 组件如何使用
----

[](#如何使用)

### 手动

[](#手动)

生成id

```
$id = \Yii::$app->snowflake->id();
// 401621641244704768
```

解析id

```
\Yii::$app->snowflake->parseId($id);
//[
//    'timestamp' => '1011001001011011000110000010011110010'
//    'sequence' => '000000000000'
//    'workerid' => '00000'
//    'datacenter' => '00000'
//]
```

### 使用Behavior自动生成id

[](#使用behavior自动生成id)

本组件支持通过附加ActiveRecord Model的behavior方式来完成自动生成id

使用下列语法:

```
public function behaviors()
{
    return [
        'snowflake' => [
            'class' => '\bestyii\snowflake\SnowflakeBehavior',
            'attributes' => 'id',// default:id
        ],
    ];
}
```

在数据保存之前, 该behavior(行为)会自动生成id.

雪花算法说明
------

[](#雪花算法说明)

本项目基于 [godruoyi/php-snowflake](https://github.com/godruoyi/php-snowflake) 实现.

[![snowflake-algorithm](snowflake-algorithm.png)](snowflake-algorithm.png)

Snowflake 是 Twitter 内部的一个 ID 生算法，可以通过一些简单的规则保证在大规模分布式情况下生成唯一的 ID 号码。其组成为：

- 第一个 bit 为未使用的符号位。
- 第二部分由 41 位的时间戳（毫秒）构成，他的取值是当前时间相对于某一时间的偏移量。
- 第三部分和第四部分的 5 个 bit 位表示数据中心和机器ID，其能表示的最大值为 2^5 -1 = 31。
- 最后部分由 12 个 bit 组成，其表示每个工作节点每毫秒生成的序列号 ID，同一毫秒内最多可生成 2^12 -1 即 4095 个 ID。

需要注意的是：

- 在分布式环境中，5 个 bit 位的 datacenter 和 worker 表示最多能部署 31 个数据中心，每个数据中心最多可部署 31 台节点 -41 位的二进制长度最多能表示 2^41 -1 毫秒即 69 年，所以雪花算法最多能正常使用 69 年，为了能最大限度的使用该算法，你应该为其指定一个开始时间。

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1361d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/383284?v=4)[Yang](/maintainers/ezsky)[@ezsky](https://github.com/ezsky)

---

Top Contributors

[![ezsky](https://avatars.githubusercontent.com/u/383284?v=4)](https://github.com/ezsky "ezsky (1 commits)")

---

Tags

uuidyii2extensionsnowflakeid-generatorbestyii.com

### Embed Badge

![Health badge](/badges/bestyii-yii2-snowflake/health.svg)

```
[![Health](https://phpackages.com/badges/bestyii-yii2-snowflake/health.svg)](https://phpackages.com/packages/bestyii-yii2-snowflake)
```

###  Alternatives

[dmstr/yii2-cookie-consent

Yii2 Cookie Consent Widget

1452.6k](/packages/dmstr-yii2-cookie-consent)[richardfan1126/yii2-js-register

Yii2 widget to register JS into view

1357.2k7](/packages/richardfan1126-yii2-js-register)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
