PHP code example of allnetru / laravel-sharding

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

    

allnetru / laravel-sharding example snippets


// config/sharding.php
return [
    'default' => 'hash',

    'strategies' => [
        'hash' => Allnetru\Sharding\Strategies\HashStrategy::class,
        'redis' => Allnetru\Sharding\Strategies\RedisStrategy::class,
        'range' => Allnetru\Sharding\Strategies\RangeStrategy::class,
        'db_range' => Allnetru\Sharding\Strategies\DbRangeStrategy::class,
        'db_hash_range' => Allnetru\Sharding\Strategies\DbHashRangeStrategy::class,
    ],

    'id_generator' => [
        'default' => 'snowflake',
        'strategies' => [
            'snowflake' => Allnetru\Sharding\IdGenerators\SnowflakeStrategy::class,
            'sequence' => Allnetru\Sharding\IdGenerators\TableSequenceStrategy::class,
        ],
        'sequence_table' => 'shard_sequences',
        // 'meta_connection' => 'pgsql', // use any connection name configured in database.php
    ],

    'connections' => [
        'shard-1' => ['weight' => 2],
        'shard-2' => ['weight' => 1],
        // 'shard-archive' => ['weight' => 1, 'replica' => true],
    ],

    'replica_count' => 1,

    'tables' => [
        // 'users' => [
        //     'strategy' => 'redis',
        //     'redis_connection' => 'shards',
        //     'redis_prefix' => 'user_shard:',
        //     'group' => 'user_data',
        // ],

        'users' => [
            'strategy' => 'db_hash_range',
            'slot_size' => 250_000,
            'connections' => [
                'shard-1' => ['weight' => 2],
                'shard-2' => ['weight' => 1],
            ],
            'meta_connection' => 'mysql',
            'group' => 'user_data',
        ],

        'profiles' => [
            // inherits the shard selected for the `users` table
            'group' => 'user_data',
            // 'id_generator' => 'sequence',
        ],

        'orders' => [
            'strategy' => 'db_range',
            'connections' => [
                'shard-1' => ['weight' => 2],
                'shard-2' => ['weight' => 1],
            ],
            'range_size' => 50_000,
            'meta_connection' => 'mysql',
            // 'range_table' => 'order_ranges',
        ],

        // 'payments' => [
        //     'strategy' => 'range',
        //     'ranges' => [
        //         ['start' => 1, 'end' => 1_000_000, 'connection' => 'shard-1'],
        //         ['start' => 1_000_001, 'end' => null, 'connection' => 'shard-2'],
        //     ],
        // ],
    ],

    'groups' => [
        'user_data' => ['users', 'profiles', 'orders'],
        // 'billing' => ['payments', 'refunds'],
    ],
];

// config/database.php (excerpt)

use Allnetru\Sharding\Support\Config\Shards;

return [
    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => array_merge([
        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DB_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            // ... keep the rest of your base connection definition
        ],

        // other non-sharded connections...
    ], Shards::databaseConnections(env('DB_SHARDS', ''))),

    // ...
];

Schema::create('items', function (Blueprint $table) {
    $table->unsignedBigInteger('id')->primary();
    $table->boolean('is_replica')->default(false);
    $table->timestamps();
});

'groups' => [
    'user_data' => ['users', 'organizations', 'billing', 'transactions'],
],

$user = User::find(15);

$partners = Organization::where('status', OrganizationStatus::partner)
    ->paginate(50);

app(ShardMover::class)->move(
    new Parcel(),
    ['parcels', 'buildings', 'tasks'],
    from: $oldTenantId,
    to: $newTenantId,
    filter: fn ($query) => $query->where('settlement_id', $settlement->getKey()),
);

// a group can key its tables differently, and name their rows differently:
// give the column, or the model, per table
app(ShardMover::class)->move(new User(), [
    'user_roles' => UserRole::class,
    'user_permissions' => UserPermission::class,
], from: $userId, to: $keptUserId);

$parcel->transaction(fn () => ...);

Parcel::query()->where('tenant_id', $tenantId)->transaction(fn () => ...);

'coroutines' => [
    'default' => env('SHARDING_COROUTINE_DRIVER', 'swoole'),
    'drivers' => [
        'swoole' => Allnetru\Sharding\Support\Coroutine\Drivers\SwooleCoroutineDriver::class,
        'sync' => Allnetru\Sharding\Support\Coroutine\Drivers\SyncCoroutineDriver::class,
        'amphp' => App\Sharding\AmpCoroutineDriver::class,
    ],
],
bash
php artisan vendor:publish --tag=laravel-sharding-config
php artisan vendor:publish --tag=laravel-sharding-migrations
bash
php artisan migrate