# Snowflake ID Generator 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: ```bash composer require lizhineng/snowflake ``` **Requirements:** PHP 8.2 or higher ## Quick Start ```php 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`: ```php Timestamp::make(); ``` Optionally set a custom epoch via the third parameter—accepts a `DateTime` object or an integer (milliseconds since Unix epoch): ```php $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. ```php // 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. ```php // 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): ```php $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 ```bash composer run test ``` ## License MIT License. See [LICENSE](LICENSE) for details.