PHP code example of hejunjie / id-generator

1. Go to this page and download the library: Download hejunjie/id-generator 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/ */

    

hejunjie / id-generator example snippets


use Hejunjie\IdGenerator\Contracts\Generator;
use Hejunjie\IdGenerator\IdGenerator;

// ----------------------------
// 1. Snowflake generation and parsing
// Returns: Snowflake ID (1-bit sign + 41-bit timestamp + 10-bit machine ID + 12-bit sequence)
// ----------------------------
echo "=== Snowflake generation and parsing ===\n";
// Optional parameters: useFileLock and redisConfig
// Without lock: uses a random sequence to simulate Snowflake ID; generating >75 IDs per millisecond may cause duplicates
// With file lock: pass useFileLock => true; no duplicates, but performance may decrease
// With Redis lock (recommended): pass redisConfig; no duplicates, uses process ID + random number; generating >37 IDs per millisecond per process may cause duplicates
// With file lock: pass useFileLock => true; no duplicates, but performance may decrease
// With Redis lock (recommended): pass redisConfig; no duplicates, ;

echo "\n\n";

// ----------------------------
// 4. UUID generation and parsing
// Returns: UUID (32-character string)
// ----------------------------
echo "=== UUID generation and parsing ===\n";
// Optional parameter: version
// version: UUID version, supports v1 and v4; defaults to v4 if not provided
$uuid = IdGenerator::make('uuid', ['version' => 'v4']);
$uuidId = $uuid->generate();
echo "generation ID: $uuidId\n";
// parsing
$parsedUUID = $uuid->parse($uuidId);
echo "parsing ID:\n";
print_r($parsedUUID);
echo "\n\n";

// ----------------------------
// 5. Custom strategy
// Returns: custom-prefix-random-number
// ----------------------------
echo "=== Custom generation and parsing ===\n";
// Custom generator implements the Generator interface
// Pass parameters for customization, implemented in the constructor
class MyCustomGenerator implements Generator
{
    public function __construct(private string $prefix = 'MY') {}

    public function generate(): string
    {
        return $this->prefix . '-' . random_int(1000, 9999);
    }
    public function parse(string $id): array
    {
        return ['id' => $id];
    }
}
// Register custom strategy
IdGenerator::registerStrategy('custom', function (array $config) {
    return new MyCustomGenerator($config['prefix'] ?? 'MY');
});
// Use custom strategy
$custom = IdGenerator::make('custom', ['prefix' => 'ORD']);
$customId = $custom->generate();
echo "generation ID: $customId\n";
// parsing
$parsedCustom = $custom->parse($customId);
echo "parsing ID:\n";
print_r($parsedCustom);
echo "\n\n";