PHP code example of highperapp / uuid

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

    

highperapp / uuid example snippets


   // Test FFI with absolute path
   $ffi = FFI::cdef("", __DIR__ . "/rust/target/release/libuuid_ffi.so");
   

use HighPerApp\HighPer\Uuid\Core\UuidFactory;

// Generate UUIDs
$uuid4 = UuidFactory::v4();  // Random UUID
$uuid7 = UuidFactory::v7();  // Timestamp-based UUID (recommended)
$uuid1 = UuidFactory::v1();  // Legacy timestamp + MAC

// Name-based UUIDs
$uuid3 = UuidFactory::v3(UuidFactory::NAMESPACE_DNS, 'example.com');
$uuid5 = UuidFactory::v5(UuidFactory::NAMESPACE_DNS, 'example.com');

// Convert and validate
$uuid = UuidFactory::fromString('550e8400-e29b-41d4-a716-446655440000');
$isValid = UuidFactory::isValid($uuid->toString());

echo $uuid->toString();   // 550e8400-e29b-41d4-a716-446655440000
echo $uuid->getVersion(); // 4

$uuid = UuidFactory::v1();
echo $uuid->getTimestamp(); // Gregorian timestamp
echo $uuid->getNode();      // MAC address (or random)

$uuid = UuidFactory::v3Dns('example.com');
// Always generates the same UUID for the same input

$uuid = UuidFactory::v4();
// Cryptographically random

$uuid = UuidFactory::v5Url('https://example.com');
// Always generates the same UUID for the same input

$uuid = UuidFactory::v6();
// Like v1 but with better database locality

$uuid = UuidFactory::v7();
// Best for new applications - sortable and efficient

$uuid = UuidFactory::v8([
    'custom_fields' => [
        'timestamp' => time(),
        'counter' => 123
    ]
]);

use HighPerApp\HighPer\Uuid\Core\Configuration;
use HighPerApp\HighPer\Uuid\Core\UuidFactory;

$config = Configuration::highPerformance();
UuidFactory::configure($config);

// Now all UUID generation uses Rust FFI when available
$uuid = UuidFactory::v4(); // Uses Rust acceleration

$config = Configuration::default()
    ->setDefaultVersion(7)
    ->setRandomProvider('rust')
    ->enableFFI(true)
    ->setMaxConcurrentWorkers(8);

UuidFactory::configure($config);

use HighPerApp\HighPer\Uuid\Core\ThreadSafeUuidFactory;

// Safe for concurrent environments
$factory = ThreadSafeUuidFactory::getInstance();
$uuid = $factory->v4();

// Or use static convenience methods
$uuid = ThreadSafeUuidFactory::createV4();
$uuid = ThreadSafeUuidFactory::createV7();

use HighPerApp\HighPer\Uuid\Async\AsyncUuidFactory;

// Check if async is available
if (AsyncUuidFactory::isAsyncAvailable()) {
    // Single async UUID
    $uuid = AsyncUuidFactory::v4Async()->await();
    $uuid = AsyncUuidFactory::v7Async()->await();

    // Batch generation (non-blocking)
    $uuids = AsyncUuidFactory::generateBatch(1000, 4)->await();

    // Concurrent batch with worker processes
    $uuids = AsyncUuidFactory::generateConcurrentBatch(10000, 4, 8)->await();
} else {
    // Fallback to synchronous
    $uuids = AsyncUuidFactory::generateBatchLegacy(1000, 4);
}

use HighPerApp\HighPer\Uuid\Async\TrueConcurrentGenerator;

// True parallel processing (generateConcurrent(100000, 4);
// Generates 100,000 UUIDs across 8 actual parallel processes

use HighPerApp\HighPer\Uuid\Async\AsyncUuidFactory;

// Stream-based generation with non-blocking yields
foreach (AsyncUuidFactory::generatePipeline(10000, 7, 1000) as $uuid) {
    // Process each UUID as it's generated
    // Automatically yields control between batches
    echo $uuid->toString() . "\n";
}

use HighPerApp\HighPer\Uuid\Configuration\AsyncConfiguration;

// Configure for high-throughput
$config = AsyncConfiguration::highThroughput();
AsyncUuidFactory::configure($config);

// Or custom configuration
$config = new AsyncConfiguration([
    'defaultWorkerCount' => 8,
    'batchSize' => 5000,
    'enableEntropyPool' => true,
    'enableParallel' => true,
]);

// Get optimal settings for your system
$optimal = $config->getOptimalWorkerCount(); // Auto-detects CPU cores
$batchSize = $config->getOptimalBatchSize(100000);

use HighPerApp\HighPer\Uuid\RandomProvider\RandomProviderFactory;

// Available providers
$providers = RandomProviderFactory::getAvailableProviders();
// ['secure', 'openssl', 'rust', 'pseudo']

// Create specific provider
$provider = RandomProviderFactory::create('rust');
$uuid = UuidFactory::v4($provider);

// Benchmark providers
$results = RandomProviderFactory::benchmark('rust', 1000);

use HighPerApp\HighPer\Uuid\Concurrency\CollisionPrevention;

// Enable collision detection
$config = Configuration::default()
    ->enableCollisionPrevention(true);
UuidFactory::configure($config);

// The library automatically handles:
// - Timestamp collisions
// - High-frequency generation
// - Multi-process safety
// - Sequence management

// In a Laravel service provider
use HighPerApp\HighPer\Uuid\Core\ThreadSafeUuidFactory;
use HighPerApp\HighPer\Uuid\Async\AsyncUuidFactory;
use HighPerApp\HighPer\Uuid\Configuration\AsyncConfiguration;

public function register()
{
    // Register thread-safe factory
    $this->app->singleton(ThreadSafeUuidFactory::class, function() {
        return ThreadSafeUuidFactory::getInstance();
    });
}

public function boot()
{
    // Configure async capabilities if available
    if (AsyncUuidFactory::isAsyncAvailable()) {
        AsyncUuidFactory::configure(AsyncConfiguration::highThroughput());
    }
}

// In your models
protected $keyType = 'string';
public $incrementing = false;

protected static function boot()
{
    parent::boot();
    
    static::creating(function ($model) {
        if (empty($model->id)) {
            $factory = app(ThreadSafeUuidFactory::class);
            $model->id = $factory->v7()->toString();
        }
    });
}

// In queue jobs for bulk operations
class BulkUuidGenerationJob
{
    public function handle()
    {
        if (AsyncUuidFactory::isAsyncAvailable()) {
            $uuids = AsyncUuidFactory::generateConcurrentBatch(50000, 7, 4)->await();
        } else {
            $uuids = AsyncUuidFactory::generateBatchLegacy(50000, 7);
        }
        
        // Process the UUIDs
    }
}

// In a service or controller
use HighPerApp\HighPer\Uuid\Core\ThreadSafeUuidFactory;
use HighPerApp\HighPer\Uuid\Async\AsyncUuidFactory;

class UuidService
{
    public function __construct(
        private ThreadSafeUuidFactory $uuidFactory
    ) {}
    
    public function generateSingle(): string
    {
        return $this->uuidFactory->v7()->toString();
    }
    
    public async function generateBatch(int $count): array
    {
        if (AsyncUuidFactory::isAsyncAvailable()) {
            return AsyncUuidFactory::generateBatch($count, 7)->await();
        }
        
        return AsyncUuidFactory::generateBatchLegacy($count, 7);
    }
}

use Swoole\Http\Server;
use HighPerApp\HighPer\Uuid\Core\ThreadSafeUuidFactory;
use HighPerApp\HighPer\Uuid\Async\AsyncUuidFactory;

$server = new Server("127.0.0.1", 9501);

$server->on('WorkerStart', function($server, $workerId) {
    // Reset static state for each worker
    ThreadSafeUuidFactory::resetInstance();
    AsyncUuidFactory::reset();
});

$server->on('Request', function($request, $response) {
    // Thread-safe UUID generation
    $factory = ThreadSafeUuidFactory::getInstance();
    $uuid = $factory->v7()->toString();
    
    $response->end("Generated UUID: {$uuid}");
});

$server->start();

use React\EventLoop\Loop;
use React\Http\HttpServer;
use HighPerApp\HighPer\Uuid\Core\ThreadSafeUuidFactory;
use HighPerApp\HighPer\Uuid\Async\AsyncUuidFactory;

$loop = Loop::get();

$server = new HttpServer(function($request) {
    return new Promise(function($resolve) {
        if (AsyncUuidFactory::isAsyncAvailable()) {
            // Non-blocking UUID generation
            AsyncUuidFactory::generateBatch(1000, 7)->then(function($uuids) use ($resolve) {
                $resolve(new Response(200, [], json_encode($uuids)));
            });
        } else {
            // Fallback to thread-safe synchronous
            $factory = ThreadSafeUuidFactory::getInstance();
            $uuids = [];
            for ($i = 0; $i < 1000; $i++) {
                $uuids[] = $factory->v7()->toString();
            }
            $resolve(new Response(200, [], json_encode($uuids)));
        }
    });
});

$socket = new SocketServer('127.0.0.1:8080', [], $loop);
$server->listen($socket);
$loop->run();

$config = new Configuration();

// Version settings
$config->setDefaultVersion(7);              // Default: 7

// Performance settings  
$config->enableFFI(true);                   // Default: true
$config->preferRustFFI(true);               // Default: true
$config->setMaxConcurrentWorkers(8);        // Default: 4

// Security settings
$config->setRandomProvider('secure');       // Default: 'secure'
$config->enableCollisionPrevention(true);   // Default: true

// Timestamp settings
$config->enableMonotonicTimestamp(true);    // Default: true
$config->setTimestampPrecision(1000);       // microseconds

// Namespaces
$config->addNamespace('custom', 'your-namespace-uuid');

use HighPerApp\HighPer\Uuid\Exception\GenerationException;
use HighPerApp\HighPer\Uuid\Exception\ValidationException;
use HighPerApp\HighPer\Uuid\Exception\ConfigurationException;

try {
    $uuid = UuidFactory::v3('invalid-namespace', 'name');
} catch (ValidationException $e) {
    // Handle validation errors
}

try {
    $uuid = UuidFactory::generate(99); // Invalid version
} catch (GenerationException $e) {
    // Handle generation errors
}
bash
   # Ubuntu/Debian
   sudo apt update
   sudo apt install php8.3-ffi php8.3-dev
   
   # CentOS/RHEL/Fedora
   sudo yum install php-ffi php-devel
   # or for newer versions:
   sudo dnf install php-ffi php-devel
   
   # macOS (with Homebrew)
   brew install php
   # FFI is usually 
bash
   php -m | grep ffi
   # Should output: ffi
   
   # Test FFI functionality
   php -r "echo extension_loaded('ffi') ? 'FFI enabled' : 'FFI not available';"
   
bash
   # Check if FFI is installed
   php -m | grep ffi
   
   # Check PHP configuration
   php --ini | grep "Configuration File"
   
   # Enable FFI in php.ini
   echo "extension=ffi" | sudo tee -a /etc/php/8.3/cli/php.ini
   
bash
   # Set FFI preload in php.ini (optional for better performance)
   echo "ffi.preload=" | sudo tee -a /etc/php/8.3/cli/php.ini
   
bash
# Run built-in benchmarks (arks --report=default

# Quick performance test
php -r "
\$i < 10000; \$i++) { UuidFactory::v4(); }
\$duration = microtime(true) - \$start;
echo 'Generated ' . number_format(10000 / \$duration) . ' UUIDs/second\n';
"
bash
   # Check ep -E "(ffi|openssl|json)"
   
   # Install missing extensions (Ubuntu/Debian)
   sudo apt install php8.3-ffi php8.3-openssl php8.3-json php8.3-dev
   
   # CentOS/RHEL/Fedora
   sudo yum install php-ffi php-openssl php-json php-devel
   
   # macOS (with Homebrew)
   brew install php
   
   # Verify FFI is working
   php -r "echo extension_loaded('ffi') ? 'FFI: ✓' : 'FFI: ✗';"