Luminova Framework

PHP Luminova: Opening Database Connection

Last updated: 2026-10-26 20:20:36

Learn how to open database connections in Luminova using PDO or MySQLi, with support for connection pooling, sharding, and automatic failover.

Databases are essential in application development for storing and managing data. Luminova's Connection class simplifies database connectivity, offering support for connection pooling and sharding to boost performance and scale with your application.

Getting Started

Establishing a connection in Luminova is straightforward. Define your connection settings in the .env file or in the App\Config\Database class. For a comprehensive guide, see Database Example.

Example .env configuration:

database.hostname = localhost
database.port = 3306
database.connection = PDO
database.pdo.version = mysql
database.username = root
database.name = my_db
database.password = password

Connection behavior settings:

KeyDefaultDescription
database.connection.poolfalseEnables connection pooling.
database.max.connections3Maximum number of pooled connections. Only applied when pooling is enabled.
database.connection.retry1Number of connection attempts before falling back to backup servers.

Additional Notes

  • CLI Access (MySQL):If you're running commands via the CLI and using MySQL, specify your socket path using:

    database.socket.path = /path/to/mysql.sock

    If this is not set, the driver falls back to pdo_mysql.default_socket (PDO) or mysqli.default_socket (MySQLi) from your php.ini. A DatabaseException is thrown when neither is available.

  • SQLite Configuration:To use SQLite, define the full database path in:

    database.sqlite.path = writeable/database/production.sqlite

    Make sure the file is located under /writeable/database/.


Configuration Class

This configuration class allows you to define backup database servers, or the server locations used for sharding when it is enabled. For more information see Database Connection Configuration.

// /app/Config/Database.php

namespace App\Config;

use Luminova\Config\DatabaseConfig;

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

    protected static array $databaseServers = [
        'NG' => [
            'host'       => 'ng.db.server.com',
            'port'       => 3306,
            'database'   => 'my_ng_db',
            'connection' => 'pdo',
            'pdo_driver' => 'mysql',
            'username'   => 'user_ng',
            'password'   => 'secret',
            'charset'    => 'utf8mb4',
        ],
        'US' => [
            'host' => 'us.db.server.com',
            // ...
        ],
        'DEFAULT' => [
            'host' => 'main.db.server.com',
            // ...
        ]
    ];

    public static function getShardServerIdentifier(): string|int|null
    {
        // Example
        return request()->header->get('X-User-Region', 'DEFAULT');
    }
}

When connect() runs (including through new Connection or Connection::getInstance()) and sharding is enabled, the connection calls getShardServerIdentifier() to pick the shard, unless an identifier was already set with shard() or setShardIdentifier(). The identifier must match a key in $databaseServers, otherwise a DatabaseException is thrown.

When sharding is disabled, $databaseServers acts as a list of failover servers. If the environment has no default connection settings, the first server in the list is used as the primary.


Basic Initialization

Create a new connection with optional connection pooling:

use Luminova\Database\Connection;

$enablePool = true;
$maxConnections = 5;
$autoConnect = true;

$conn = new Connection($enablePool, $maxConnections, $autoConnect);

Singleton Instance

Retrieve a shared connection instance. Pooling and connection limits are read from the environment, and sharding is applied automatically when enabled:

use Luminova\Database\Connection;

$conn = Connection::getInstance();

Manual Shard Connection

Connect to a specific shard by its identifier:

use Luminova\Database\Connection;

$conn = Connection::shard(
    'NG',    // Shard identifier (e.g., region or server key)
    false,   // Fall back to backup servers on connection error
    null     // Connection pooling (null uses the environment setting)
);

Custom Configuration

Create a standalone driver from a configuration object, without pooling or sharding:

use App\Config\Database;
use Luminova\Database\Connection;

$conn = Connection::with(Database::fromArray([
    'host'       => 'localhost',
    'port'       => 3306,
    'database'   => 'my_db',
    'connection' => 'pdo',
    'pdo_driver' => 'mysql',
    'username'   => 'root',
    'password'   => 'password',
]));

$query = $conn->query('SELECT * FROM users');

Class Definition


Properties

Database connection driver instance.

protected ?Luminova\Interface\DatabaseDriverInterface $db = null;

Methods

__construct

Create a new database connection instance.

Initializes the connection with optional settings for pooling and maximum connections.

If not explicitly provided, values are loaded from environment variables:

  • database.connection.pool for pooling (default: false).
  • database.max.connections for maximum connections (default: 3, only used when pooling is enabled).

When $autoConnect is true, the connection is automatically established on instantiation.

public __construct(?bool $connectionPooling = null, ?int $maxPoolConnections = null, bool $autoConnect = true)

Parameters:

ParameterTypeDescription
$connectionPoolingbool|nullWhether to enable connection pooling.
Overrides the database.connection.pool environment setting if set.
$maxPoolConnectionsint|nullMaximum number of pooled connections. Must be greater than zero.
Overrides database.max.connections from the environment if set.
$autoConnectboolWhether to immediately initiate the database connection (default: true).

Throws:


getInstance

Returns the shared singleton instance of the connection class.

Creates a new instance if one does not already exist, using the environment values for pooling and maximum connections, and connects immediately.

public static getInstance(): static

Return Value:

Luminova\Database\Connection - Return the singleton instance of the Connection class.

Throws:


shard

Create a new connection instance for a specific shard server.

This method returns a new instance on every call, it does not reuse the singleton. If the selected shard is unreachable, it can fall back to the configured backup servers.

public static shard(
  string|int $identifier, 
  bool $fallbackOnError = false,
  ?bool $connectionPooling = null
): static

Parameters:

ParameterTypeDescription
$identifierstring|intShard identifier (e.g., region name or server key). Must not be empty or a negative integer.
$fallbackOnErrorboolFall back to a backup server if the shard server connection is unavailable (default: false).
$connectionPoolingbool|nullEnables or disables connection pooling. null uses the environment setting.

Return Value:

Luminova\Database\Connection - Returns an initialized database connection instance.

Throws:


with

Create a database driver from the given configuration.

The returned driver is not stored in the connection instance, and neither pooling nor sharding is applied.

public static with(Luminova\Config\DatabaseConfig $config): ?DatabaseDriverInterface

Parameters:

ParameterTypeDescription
$configLuminova\Config\DatabaseConfigDatabase connection configuration. The connection value must be pdo or mysqli.

Return Value:

Luminova\Interface\DatabaseDriverInterface|null - Returns a connected driver, or null if the connection fails.

Throws:


database

Retrieves the database driver connection object.

public database(): ?DatabaseDriverInterface

Return Value:

Luminova\Interface\DatabaseDriverInterface|null - Return the driver instance (Luminova\Database\Driver\PdoDriver or Luminova\Database\Driver\MysqliDriver), or null if not connected.

Examples:

Using the Driver Object

$driver = $conn->database(); // Get the driver instance

$driver->query('SELECT * FROM users');
print_r($driver->fetchAll());

getDriverConn

Retrieves the driver connection wrapper, which gives access to the native PDO or mysqli object.

The wrapper also proxies method calls to the native object, so $conn->getDriverConn()->query(...) calls the native query method directly.

public getDriverConn(): ?DriverConnectionInterface

Return Value:

Luminova\Interface\DriverConnectionInterface|null - Return the connection wrapper, or null if the driver is unavailable.

Examples:

Using the Native Connection (PDO/MySQLi)

$native = $conn->getDriverConn()->getConn(); // PDO, mysqli, or null

$stmt = $native->query('SELECT * FROM users'); // PDOStatement when using PDO
print_r($stmt->fetchAll());

Use getConn() when you need direct access to low-level methods or driver-specific functionality. Native return values differ between PDO and MySQLi, so check isPdo() or isMysqli() first when your code supports both.


connect

Establish a database connection.

Returns the current connection if it is still connected. Otherwise, it tries to connect using the retry count from database.connection.retry, then falls back to the backup servers defined in the App\Config\Database class.

When sharding is enabled and no shard identifier is set, the identifier is resolved from getShardServerIdentifier(), and $shardFallbackOnError is applied.

public connect(): ?DatabaseDriverInterface

Return Value:

Luminova\Interface\DatabaseDriverInterface|null - Return the connected driver instance, or null if all attempts fail in production.

Throws:

  • \Luminova\Exceptions\DatabaseException - If all attempts fail in non-production mode, the maximum connection limit is reached, an invalid database driver is provided, or an error occurs during connection.

In production, failed attempts are logged as critical and null is returned instead of throwing.This method returns the driver without storing it on the instance. If you created the connection with $autoConnect = false, keep the returned object.


disconnect

Frees up the statement cursor, closes the current database connection, and clears the driver from the instance.

public disconnect(): bool

Return Value:

bool - Return true if disconnected, false otherwise.

Note: To close all connections including pools use the purge method instead.


retry

Attempts to reconnect to the database with optional fallback to backup servers.

If a connection is already active, it is returned. When pooling is enabled, a free pooled connection is reused first.

If $retry is set to null, the method tries each server in $databaseServers until one connects. When a shard is set and shard fallback is disabled, it returns null instead.

Otherwise, it makes up to $retry attempts (minimum of 1). When a shard is set, the shard server is tried first.

public retry(?int $retry = 1): ?DatabaseDriverInterface

Parameters:

ParameterTypeDescription
$retryint|nullThe number of retry attempts (default: 1). Pass null to attempt fallback to backup servers.

Return Value:

Luminova\Interface\DatabaseDriverInterface|null - Returns a database connection if successful, or null if all attempts fail.

Throws:

  • \Luminova\Exceptions\DatabaseException - If the shard server is not found in the configuration, the driver is invalid, or a fatal connection error occurs. In non-production mode, any connection error is rethrown.

enableConnectionPool

Enables or disables connection pooling.

public enableConnectionPool(bool $enabled = true): self

This does not set a pool limit. If pooling was not enabled in the constructor, call setMaxPoolConnections() as well, otherwise releasing a connection to the pool throws a DatabaseException.


setMaxPoolConnections

Sets the maximum number of pooled connections.

public setMaxPoolConnections(int $connections): self

Throws:


setShardIdentifier

Sets the identifier of the shard to connect to. String values are trimmed.

public setShardIdentifier(string|int $identifier): self

Throws:


enableShardErrorFallback

Enables or disables fallback to backup servers when a shard connection fails.

public enableShardErrorFallback(bool $enabled = false): static

hasShard

Check if a shard identifier is set.

public hasShard(): bool

Return Value:

bool - Return true if a shard identifier exists, otherwise false.

Example:

use Luminova\Database\Connection;

$conn = (new Connection(autoConnect: false))
    ->setShardIdentifier('NG')
    ->enableShardErrorFallback(true);

$driver = $conn->connect(); // Keep the returned driver

getPool

Removes and returns a free connection from the pool.

If $anyFree is false, the first pooled connection is removed and returned only if it is still connected, otherwise null is returned.

If $anyFree is true, the pool is scanned and the first connected connection is removed and returned. Disconnected entries are closed and discarded along the way.

public getPool(bool $anyFree = false): ?DatabaseDriverInterface

Parameters:

ParameterTypeDescription
$anyFreeboolIf true, returns the first connected connection in the pool (default: false).

Return Value:

Luminova\Interface\DatabaseDriverInterface|null - Return a connected driver from the pool or null if none are available.


release

Releases a connection back to the connection pool.

public release(DatabaseDriverInterface $connection, string $id): void

Parameters:

ParameterTypeDescription
$connectionLuminova\Interface\DatabaseDriverInterfaceThe connection to release to the pool.
$idstringAn identifier for the connection in the pool.

Throws:


purge

Purges all pooled connections and optionally closes the current database connection.

public purge(bool $closeCurrent = false): bool

Parameters:

ParameterTypeDescription
$closeCurrentboolIf true, close the current database connection also (default: false).

Return Value:

bool - Return true when connections are closed, otherwise false.


count

Count the number of connections in the pool.

public count(): int

Return Value:

int - Return the number of pooled connections.

The pool is static, so it is shared by all Connection instances.


getOpenConnections

Get the number of currently open driver connections.

public getOpenConnections(): int

Return Value:

int - Return the number of open connections, or 0 if no driver is available.


Serialization

When serialized, the connection stores the driver's configuration array, or an empty array if there is no driver. On unserialize, it reconnects using that configuration, or the default settings when the array is empty.

The serialized data contains the connection configuration, including credentials. Avoid persisting it in untrusted storage.