1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
# 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
Run the test suite locally:
```bash
composer test
```
Test across all PHP versions and dependency modes:
```bash
composer matrix
```
## License
MIT License. See [LICENSE](LICENSE) for details.
|