PHP code example of bmilleare / sonyflake-php

1. Go to this page and download the library: Download bmilleare/sonyflake-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bmilleare / sonyflake-php example snippets


use Bmilleare\Sonyflake\Settings;
use Bmilleare\Sonyflake\Sonyflake;

$sf = new Sonyflake(new Settings(machineId: 1));

$id = $sf->nextId();           // e.g. 70368744177665
$parts = $sf->decompose($id);  // Decomposed { id, time, sequence, machine }

use Bmilleare\Sonyflake\MachineId\FileLeaseStore;
use Bmilleare\Sonyflake\MachineId\LeasedResolver;
use Bmilleare\Sonyflake\Settings;
use Bmilleare\Sonyflake\Sonyflake;

$resolver = new LeasedResolver(new FileLeaseStore('/var/run/sonyflake'));
$sf = new Sonyflake(new Settings(machineId: $resolver));

use Bmilleare\Sonyflake\MachineId\Lease;
use Bmilleare\Sonyflake\MachineId\LeaseStore;

final class RedisLeaseStore implements LeaseStore
{
    public function acquire(int $maxId): Lease { /* atomic INCR with TTL */ }
    public function renew(Lease $lease): void { /* refresh TTL */ }
    public function release(Lease $lease): void { /* DEL */ }
}

new Settings(
    startTime: new DateTimeImmutable('2025-01-01T00:00:00Z'),
    bitsSequence: 8,                       // 0..30
    bitsMachineId: 16,                     // 0..30; time = 63 − seq − machine ≥ 32
    timeUnitNanos: 10_000_000,             // 10 ms; min 1 ms
    machineId: $resolver,                  // int | MachineIdResolver | null (null → PrivateIpResolver)
    checkMachineId: fn (int $id) => true,  // optional validation
    clock: null,                           // null → SystemClock; inject for tests
);

use Bmilleare\Sonyflake\Clock\Clock;

final class FrozenClock implements Clock
{
    public function __construct(private int $now) {}
    public function nowNanos(): int { return $this->now; }
    public function sleepNanos(int $nanos): void { $this->now += max(0, $nanos); }
}
bash
composer 
bash
php examples/basic.php    # explicit machine id, default v2 layout
php examples/leased.php   # two simulated FPM workers leasing distinct slots