Laravel Snowflake

repository·main·Indexed 41 days ago

https://github.com/kra8/laravel-snowflake

A package for Laravel and Lumen applications that generates 64-bit identifiers based on the Snowflake algorithm for use as primary keys. It includes the HasSnowflakePrimary trait for Eloquent models, a HasShortflakePrimary trait for 53-bit JavaScript-compatible IDs, and a Snowflake class for manual ID generation and parsing.

Tokens
1.7K
Snippets
12
Records
12
Agent score
52%

What's inside Laravel Snowflake

  1. Use Snowflake primary keys with Eloquent

    main

    To use snowflake identifiers as primary keys in your Eloquent models, use the Kra8\Snowflake\HasSnowflakePrimary trait. This trait automatically sets the $incrementing property to false and configures the model to use the snowflake type.

    Ensure your database migration uses the id() column type (which maps to a 64-bit integer).

    namespace App;
    
    use Kra8\Snowflake\HasSnowflakePrimary;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable
    {
        use HasSnowflakePrimary;
    }
  2. Use Shortflake primary keys for JavaScript compatibility

    main

    Standard 64-bit integers can cause precision issues in JavaScript. To generate a 53-bit integer that can be safely handled by JavaScript, use the Kra8\Snowflake\HasShortflakePrimary trait instead of HasSnowflakePrimary in your Eloquent model.

    namespace App;
    
    use Kra8\Snowflake\HasShortflakePrimary;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable
    {
        use HasShortflakePrimary;
    }
  3. Install Laravel Snowflake

    main

    To install the package in a Laravel project, use Composer to require the package and then publish the provider configuration.

    composer require "kra8/laravel-snowflake"
    php artisan vendor:publish --provider="Kra8\Snowflake\Providers\LaravelServiceProvider"
    composer require "kra8/laravel-snowflake"
    
    php artisan vendor:publish --provider="Kra8\Snowflake\Providers\LaravelServiceProvider"
  4. Install Laravel Snowflake in Lumen

    main

    To install the package in a Lumen project, first install via Composer, then manually register the service provider in your bootstrap/app.php file.

    composer require "kra8/laravel-snowflake"
    // In bootstrap/app.php
    $app->register(Kra8\Snowflake\Providers\LumenServiceProvider::class);
  5. Publish the Snowflake configuration file

    main

    To customize the package settings, you can publish the snowflake.php configuration file to your application's config directory using the Laravel vendor:publish command. This allows you to manage Snowflake connection details and other package options within your own codebase.

    php artisan vendor:publish --provider="Kra8\Snowflake\Providers\LaravelServiceProvider"
  6. Generate snowflake identifiers manually

    main

    You can resolve the Snowflake instance from the service container using the Kra8\Snowflake\Snowflake class and then call the next() method to generate a new 64-bit identifier.

    $snowflake = app('Kra8\Snowflake\Snowflake');
    $id = $snowflake->next();
  7. Generate 53-bit short IDs with Snowflake::short()

    main

    If you require smaller identifiers, the short() method generates a 53-bit ID. This ID is composed only of the timestamp bits (41) and the sequence bits (12), omitting the datacenter and worker ID components.

    use Kra8\Snowflake\Snowflake;
    
    $snowflake = new Snowflake();
    $shortId = $snowflake->short();
  8. Generate unique 64-bit IDs with Snowflake::next()

    main

    The next() method (and its alias id()) generates a unique 64-bit integer identifier based on the Snowflake algorithm. It incorporates a timestamp, datacenter ID, worker ID, and a sequence number to ensure uniqueness across distributed systems.

    To use it, instantiate the Snowflake class with your specific workerId and datacenterId to prevent collisions between different nodes.

    use Kra8\Snowflake\Snowflake;
    
    // Initialize with custom worker and datacenter IDs
    $snowflake = new Snowflake(null, 1, 1);
    
    // Generate a 64-bit ID
    $id = $snowflake->next();
  9. Parse a Snowflake ID into its components

    main

    The parse(int $id) method decomposes a 64-bit Snowflake ID back into its constituent parts. It returns an associative array containing the binary representations and the decoded integer values for the timestamp, sequence, worker ID, datacenter ID, and the human-readable datetime.

    use Kra8\Snowflake\Snowflake;
    
    $snowflake = new Snowflake();
    $id = $snowflake->next();
    
    $components = $snowflake->parse($id);
    
    /*
    $components will contain:
    [
        'binary_length' => string,
        'binary' => string,
        'binary_timestamp' => string,
        'binary_sequence' => string,
        'binary_worker_id' => string,
        'binary_datacenter_id' => string,
        'timestamp' => int,
        'sequence' => int,
        'worker_id' => int,
        'datacenter_id' => int,
        'epoch' => int,
        'datetime' => string (Y-m-d H:i:s),
    ]
    */
  10. Initialize the Snowflake client

    main

    The Snowflake constructor allows you to define the custom parameters for your ID generation environment:

    • ?int $timestamp: The epoch time in seconds. If null, it defaults to 2021-02-02 00:00:00.
    • int $workerId: A unique identifier for the current worker (default: 1).
    • int $datacenterId: A unique identifier for the current datacenter (default: 1).
    use Kra8\Snowflake\Snowflake;
    
    // Custom epoch (as unix timestamp), worker ID 5, datacenter ID 2
    $snowflake = new Snowflake(1612435200, 5, 2);