PHP Luminova: Database Fallback Servers & Sharding Configurations
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
- Full namespace:
App\Config\Database - File path:
/app/Config/Database.php - This class extends Luminova\Base\Database\AbstractConfig.
How Connections Are Resolved
- Default connection. The connection is built from your environment variables (
.env, or.dev.envin development). If no environment configuration exists, the first entry in$databaseServersis used instead, so always define your default server first. - Retries. If the connection fails, it is retried according to
database.connection.retry(default1). - Failover. If all retries fail, each server in
$databaseServersis tried in order until one connects. When none connects, aDatabaseExceptionis thrown outside production. In production the failure is logged andnullis returned. - Sharding. When
$connectionShardingistrue, the key returned bygetShardServerIdentifier()selects the server from$databaseServers. If the key does not exist, aDatabaseExceptionis thrown. If the shard is unreachable and$shardFallbackOnErroristrue, 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
hostanddatabasefor 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.
| Key | Type | Description |
|---|---|---|
| host | string | Hostname or IP address of the database server. Default is 'localhost'. |
| port | int | Port number of the database server. Default is 3306. |
| connection | string | Connection driver. Supported values: 'pdo', 'mysqli'. Default is 'pdo'. |
| pdo_driver | string | PDO driver type, used only when connection is 'pdo'. Supported values: 'mysql', 'sqlite', 'oci', 'dblib', 'cubrid', 'sqlsrv', 'pgsql'. Default is 'mysql'. |
| charset | string | Character set used by the connection. utf8 and utf-8 are normalized to utf8mb4. Default is 'utf8mb4'. |
| username | string | Username for authenticating with the database. Default is 'root'. Ignored for SQLite. |
| password | string | Password for the database user. Default is an empty string. Ignored for SQLite. |
| database | string | Name of the target database. Default is an empty string. |
| socket | bool | Force a UNIX socket connection. Default is false. |
| socket_path | string | Full 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_path | string | Path to the SQLite database file. Required when pdo_driver is 'sqlite'. Default is null. |
| persistent | bool | Enable persistent connections. Default is false. Persistent connections are always used in CLI mode. |
| emulate_prepares | bool | Emulate prepared statements instead of using native driver support. Default is true. |
| timeout | int | Connection timeout in seconds. Applied only when greater than 0. Default is 0. |
| buffered_query | bool | Use buffered queries. Applies to the PDO MySQL driver only. Default is false. |
| commands | list<string> | Statements to run when the connection is initialized. Only SET statements are allowed, anything else throws a DatabaseException. Default is []. |
| production | bool | Default 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.envduring development, or directly in theApp\Config\Databaseclass.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|nullReturn:
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(): arrayReturn:
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): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$config | array<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(): arrayReturn:
array<string,mixed> - The connection properties.
getValue
Returns a single connection property.
public final function getValue(string $key, mixed $default = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The configuration key, such as host. |
$default | mixed | Value 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:
| Parameter | Type | Description |
|---|---|---|
$config | array<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.