PHP code example of morozmkhl / scalable-db
1. Go to this page and download the library: Download morozmkhl/scalable-db 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/ */
morozmkhl / scalable-db example snippets
return [
'default_strategy' => 'hash',
'strategies' => [
'hash' => [
'shard_count' => 2,
'map' => [0 => 'shard_0', 1 => 'shard_1'],
],
],
'shards' => [
'shard_0' => [
'connection' => 'shard0_master',
'replicas' => ['shard0_replica1'],
],
'shard_1' => [
'connection' => 'shard1_master',
'replicas' => [],
],
],
'failover' => [
'auto_failover' => false,
'max_retries' => 1,
'fallback_connection' => null,
],
];
'strategies' => [
'hash' => [
'shard_count' => 2,
'map' => [0 => 'shard_0', 1 => 'shard_1'],
],
],
'default_strategy' => 'hash',
use ScalableDB\Facades\Shard;
Shard::forTenant($userId)->run(function () use ($userId) {
return User::find($userId);
});
'strategies' => [
'range' => [
'ranges' => [
['min' => 1, 'max' => 10000, 'shard' => 'shard_0'],
['min' => 10001, 'max' => 20000, 'shard' => 'shard_1'],
],
],
],
'default_strategy' => 'range',
Shard::forTenant($orderId)->run(function () use ($orderId) {
return Order::find($orderId);
});
'strategies' => [
'lookup' => [
'connection' => 'lookup',
'table' => 'tenants',
'key_column' => 'id',
'shard_column' => 'shard',
'cache_ttl' => 300,
],
],
'default_strategy' => 'lookup',
Shard::forTenant($tenantId)->run(function () use ($tenantId) {
return Post::where('tenant_id', $tenantId)->get();
});
'shard0_master' => [
'driver' => 'mysql',
'read' => ['host' => ['replica1.example.com']],
'write' => ['host' => ['master.example.com']],
'sticky' => true,
],
Shard::forTenant($id)->forRead()->run(fn () => User::find($id));
Shard::forTenant($id)->forWrite()->run(fn () => User::create([...]));
Route::middleware('shard.tenant')->group(function () {
Route::get('/posts', [PostController::class, 'index']);
});
use ScalableDB\Events\ShardFailover;
use Illuminate\Support\Facades\Event;
Event::listen(ShardFailover::class, function (ShardFailover $event) {
logger()->warning("Fail-over {$event->shard}: {$event->fromConnection} -> {$event->toConnection}", [
'error' => $event->exception->getMessage(),
]);
});
bash
php artisan vendor:publish --tag=scalable-db-migrations
php artisan vendor:publish --tag=scalable-db-database