lizhineng / snowflake
Build your own Snowflake.
Requires
- php: ^8.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.92
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11.5
This package is not auto-updated.
Last update: 2026-01-07 00:05:59 UTC
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.