lizhineng/snowflake
最新稳定版本:v0.1.0
Composer 安装命令:
composer require lizhineng/snowflake
包简介
Build your own Snowflake.
README 文档
README
A flexible, customizable distributed ID generator inspired by Twitter's Snowflake, built for PHP 8.2+.
Unlike traditional implementations with hard-coded structures, this package lets you build your own ID format to perfectly suit your application's needs.
Installation
The package can be installed through Composer:
composer require lizhineng/snowflake
Requirements: PHP 8.2 or higher
Quick Start
use Zhineng\Snowflake\Constant;
use Zhineng\Snowflake\Manager;
use Zhineng\Snowflake\Sequence;
use Zhineng\Snowflake\Structure;
use Zhineng\Snowflake\Timestamp;
$structure = new Structure;
$structure->add(Sequence::make('sequence', 12));
$structure->add(Constant::make('instance', 10));
$structure->add(Timestamp::make('timestamp', 41));
$manager = new Manager;
$manager->structureUsing($structure);
$id1 = $manager->nextId(); // e.g., 123456789012345678
$id2 = $manager->nextId(); // e.g., 123456789012345679
Usage
Field Types
Timestamp
Timestamp field tracks milliseconds since epoch, defaulting to 41 bits
and the name timestamp:
Timestamp::make();
Optionally set a custom epoch via the third parameter—accepts a DateTime
object or an integer (milliseconds since Unix epoch):
$epoch = new \DateTime('2026-01-01 00:00:00');
Timestamp::make('timestamp', 41, $epoch);
Constant
Fixed value field for static identifiers (e.g., datacenter ID, machine ID). Value defaults to 0 if not specified.
// Machine ID with value 5 (10 bits)
Constant::make('machine_id', 10, 5);
// Datacenter ID with value 2 (5 bits)
Constant::make('datacenter_id', 5, 2);
Sequence
Auto-incrementing sequence that resets to 0 whenever any other field changes.
An OverflowException is thrown if the value exceeds its maximum.
// 12-bit sequence (range 0-4095)
Sequence::make('sequence', 12);
Building Custom Structures
Customize the ID format to suit your needs—the structure is built from right to left (LSB to MSB):
$structure = new Structure;
// Bit layout: [timestamp:41][instance:10][sequence:12] = 63 bits
$structure->add(Sequence::make('sequence', 12));
$structure->add(Constant::make('instance', 10));
$structure->add(Timestamp::make('timestamp', 41));
echo $structure->size(); // 63
Testing
Run the test suite locally:
composer test
Test across all PHP versions and dependency modes:
composer matrix
License
MIT License. See LICENSE for details.
统计信息
- 总下载量: 4
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-06