Luminova Framework

PHP Luminova: Database Fallback Servers & Sharding Configurations

Last updated: 2026-11-28 20:57:12

Configure database sharding and backup servers for connection failover.

The Database Configuration class allows you to define your primary database connection as well as optional shard or backup servers. Backup servers are used automatically when the primary database cannot be reached. Each server is defined as a nested associative array with keys such as host, port, username, and password.

This setup enables automatic failover and supports sharding strategies based on region, user ID, or custom application logic.


Class Definition


How Connections Are Resolved

  1. Default connection. The connection is built from your environment variables (.env, or .dev.env in development). If no environment configuration exists, the first entry in $databaseServers is used instead, so always define your default server first.
  2. Retries. If the connection fails, it is retried according to database.connection.retry (default 1).
  3. Failover. If all retries fail, each server in $databaseServers is tried in order until one connects. When none connects, a DatabaseException is thrown outside production. In production the failure is logged and null is returned.
  4. Sharding. When $connectionSharding is true, the key returned by getShardServerIdentifier() selects the server from $databaseServers. If the key does not exist, a DatabaseException is thrown. If the shard is unreachable and $shardFallbackOnError is true, the remaining servers are tried as in step 3. Otherwise the connection fails without trying other servers.

Properties

connectionSharding

Enable or disable connection level database sharding.

When set to true, the application routes connections to the server whose key matches the value returned by getShardServerIdentifier(). This allows you to spread load across shard servers for scalability and isolation (for example multi-tenant or geo based setups).

public static bool $connectionSharding = false;

If false, all connections use the default configuration.


shardFallbackOnError

Whether to fall back to the other configured servers when the selected shard is unreachable.

When enabled, the system tries the servers listed in $databaseServers if the shard server fails or is offline.

public static bool $shardFallbackOnError = false;

Useful in distributed environments where high availability is required.


databaseServers

List of database connection servers.

This serves two purposes:

  • Provides the server list for sharded environments, keyed by shard identifier.
  • Acts as a failover list for non sharded environments when the main database fails.

Each server uses the same structure as the primary configuration.

/**
 * @var array<int|string, array<string, mixed>>
 */
protected static array $databaseServers = [];

A nested associative array of server keys and their configuration values. Define at least host and database for every server, since both are used in connection log messages.

Supported Configuration Keys

These keys apply to entries in $databaseServers. Unspecified keys use the defaults below.

KeyTypeDescription
hoststringHostname or IP address of the database server. Default is 'localhost'.
portintPort number of the database server. Default is 3306.
connectionstringConnection driver. Supported values: 'pdo', 'mysqli'. Default is 'pdo'.
pdo_driverstringPDO driver type, used only when connection is 'pdo'. Supported values: 'mysql', 'sqlite', 'oci', 'dblib', 'cubrid', 'sqlsrv', 'pgsql'. Default is 'mysql'.
charsetstringCharacter set used by the connection. utf8 and utf-8 are normalized to utf8mb4. Default is 'utf8mb4'.
usernamestringUsername for authenticating with the database. Default is 'root'. Ignored for SQLite.
passwordstringPassword for the database user. Default is an empty string. Ignored for SQLite.
databasestringName of the target database. Default is an empty string.
socketboolForce a UNIX socket connection. Default is false.
socket_pathstringFull path to the socket file. Falls back to pdo_mysql.default_socket or mysqli.default_socket from php.ini when empty. Default is an empty string.
sqlite_pathstringPath to the SQLite database file. Required when pdo_driver is 'sqlite'. Default is null.
persistentboolEnable persistent connections. Default is false. Persistent connections are always used in CLI mode.
emulate_preparesboolEmulate prepared statements instead of using native driver support. Default is true.
timeoutintConnection timeout in seconds. Applied only when greater than 0. Default is 0.
buffered_queryboolUse buffered queries. Applies to the PDO MySQL driver only. Default is false.
commandslist<string>Statements to run when the connection is initialized. Only SET statements are allowed, anything else throws a DatabaseException. Default is [].
productionboolDefault is false. This key is not read by the built in PDO or MySQLi drivers.

Socket connections

A UNIX socket is used instead of TCP when the application runs from the command line, when socket is true, or when running inside the novakit container. If no socket path is configured and none is set in php.ini, a DatabaseException is thrown. For PDO, sockets apply to the mysql driver only.

Init commands

commands accepts SET statements only. A SET NAMES statement must follow the form SET NAMES charset or SET NAMES charset COLLATE collation. When no SET NAMES command is given, the charset value is applied automatically. For PDO this applies to the mysql driver only.


The default connection values can be defined in your .env file, or in .dev.env during development, or directly in the App\Config\Database class.Example:

database.connection=pdo
database.pdo.driver=mysql
database.hostname=127.0.0.1
database.port=3306
database.username=root
database.password=secret
database.name=my_database

Example:

// /app/Config/Database.php

namespace App\Config;

use Luminova\Base\Database\AbstractConfig;

class Database extends AbstractConfig
{
    public static bool $connectionSharding = true;
    public static bool $shardFallbackOnError = true;

    /**
     * @var array<int|string, array<string, mixed>>
     */
    protected static array $databaseServers = [
        'DEFAULT' => [
            'host' => 'main.db.server',
            'port' => 3306,
            'database' => 'main_db',
            'connection' => 'pdo',
            'pdo_driver' => 'mysql',
            'username' => 'user_main',
            'password' => 'secret',
            'charset' => 'utf8mb4',
            'persistent' => false,
            'emulate_prepares' => true,
            'socket' => false,
            'socket_path' => '',
            'sqlite_path' => '', // Only used if pdo_driver is sqlite
            'commands' => [
                "SET time_zone = '+00:00'"
            ]
        ],
        'NG' => [
            'host' => 'ng.db.server',
            // ...
        ],
        'US' => [
            'host' => 'us.db.server',
            // ...
        ]
    ];

    public static function getShardServerIdentifier(): string|int|null
    {
        return 'NG';
    }
}

Always set the default connection as the first entry before other servers.


Methods

getShardServerIdentifier

Returns the key of the server to use when $connectionSharding is enabled. Override it to return a static value, or resolve it at runtime from the user's region or tenant. The default implementation returns null.

public static function getShardServerIdentifier(): string|int|null

Return:

string|int|null - The shard identifier, which must match a key in $databaseServers.

Example:

public static function getShardServerIdentifier(): string|int|null
{
    return Service::resolveUserRegion(); // e.g. 'NG', 'US'
}

getServers

Returns all configured database servers.

public static final function getServers(): array

Return:

array<string|int,array<string,mixed>> - The contents of $databaseServers.


fromArray

Creates a configuration instance from an array. Values you pass replace the defaults listed above.

public static function fromArray(array $config): static

Parameters:

ParameterTypeDescription
$configarray<array-key, mixed>Database configuration keys and values.

Return:

static - A configuration instance with the resolved values.


toArray

Returns the resolved connection options as an array, including defaults.

public final function toArray(): array

Return:

array<string,mixed> - The connection properties.


getValue

Returns a single connection property.

public final function getValue(string $key, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$keystringThe configuration key, such as host.
$defaultmixedValue returned when the key is not set.

Return:

mixed - The property value, or $default.


__construct

Creates a configuration instance. When $config is empty, the defaults are used.

public function __construct(array $config = [])

Parameters:

ParameterTypeDescription
$configarray<array-key, mixed>Optional values that replace the default connection options.

Connecting to a Shard

You can also pick a shard at runtime with Luminova\Database\Connection::shard(), which does not depend on $connectionSharding.

use Luminova\Database\Connection;

$conn = Connection::shard('NG', fallbackOnError: true);
$db = $conn->database();

The identifier cannot be empty or a negative integer, otherwise an InvalidArgumentException is thrown.