PHP Luminova: Opening Database Connection
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 = passwordConnection behavior settings:
| Key | Default | Description |
|---|---|---|
database.connection.pool | false | Enables connection pooling. |
database.max.connections | 3 | Maximum number of pooled connections. Only applied when pooling is enabled. |
database.connection.retry | 1 | Number 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.sockIf this is not set, the driver falls back to
pdo_mysql.default_socket(PDO) ormysqli.default_socket(MySQLi) from yourphp.ini. ADatabaseExceptionis thrown when neither is available.SQLite Configuration:To use SQLite, define the full database path in:
database.sqlite.path = writeable/database/production.sqliteMake 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
- Class namespace:
Luminova\Database\Connection - This class implements: \Luminova\Interface\LazyObjectInterface, \Countable
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.poolfor pooling (default:false).database.max.connectionsfor 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:
| Parameter | Type | Description |
|---|---|---|
$connectionPooling | bool|null | Whether to enable connection pooling. Overrides the database.connection.pool environment setting if set. |
$maxPoolConnections | int|null | Maximum number of pooled connections. Must be greater than zero. Overrides database.max.connections from the environment if set. |
$autoConnect | bool | Whether to immediately initiate the database connection (default: true). |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the maximum pool connections is less than one.
- \Luminova\Exceptions\DatabaseException - If connection retries fail, the connection limit is exceeded, an invalid driver is specified, or any error occurs during connection.
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(): staticReturn Value:
Luminova\Database\Connection - Return the singleton instance of the Connection class.
Throws:
- \Luminova\Exceptions\DatabaseException - If connection retries fail, max connection limit is reached, an invalid driver is detected, or a connection error occurs.
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
): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$identifier | string|int | Shard identifier (e.g., region name or server key). Must not be empty or a negative integer. |
$fallbackOnError | bool | Fall back to a backup server if the shard server connection is unavailable (default: false). |
$connectionPooling | bool|null | Enables or disables connection pooling. null uses the environment setting. |
Return Value:
Luminova\Database\Connection - Returns an initialized database connection instance.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If the shard identifier is empty or negative.
- \Luminova\Exceptions\DatabaseException - If the shard server is not found in
$databaseServers, connection retries fail, the max connection limit is reached, an invalid driver is detected, or a connection error occurs.
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): ?DatabaseDriverInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$config | Luminova\Config\DatabaseConfig | Database 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:
- \Luminova\Exceptions\DatabaseException - If the driver is unsupported or a connection error occurs.
database
Retrieves the database driver connection object.
public database(): ?DatabaseDriverInterfaceReturn 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(): ?DriverConnectionInterfaceReturn 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 checkisPdo()orisMysqli()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(): ?DatabaseDriverInterfaceReturn 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
nullis 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(): boolReturn Value:
bool - Return true if disconnected, false otherwise.
Note: To close all connections including pools use the
purgemethod 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): ?DatabaseDriverInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$retry | int|null | The 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): selfThis 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 aDatabaseException.
setMaxPoolConnections
Sets the maximum number of pooled connections.
public setMaxPoolConnections(int $connections): selfThrows:
- \Luminova\Exceptions\InvalidArgumentException - If
$connectionsis less than one.
setShardIdentifier
Sets the identifier of the shard to connect to. String values are trimmed.
public setShardIdentifier(string|int $identifier): selfThrows:
- \Luminova\Exceptions\InvalidArgumentException - If the identifier is empty or a negative integer.
enableShardErrorFallback
Enables or disables fallback to backup servers when a shard connection fails.
public enableShardErrorFallback(bool $enabled = false): statichasShard
Check if a shard identifier is set.
public hasShard(): boolReturn 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 drivergetPool
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): ?DatabaseDriverInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$anyFree | bool | If 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): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$connection | Luminova\Interface\DatabaseDriverInterface | The connection to release to the pool. |
$id | string | An identifier for the connection in the pool. |
Throws:
- \Luminova\Exceptions\DatabaseException - If the pool is already full. The provided connection is closed before the exception is thrown.
purge
Purges all pooled connections and optionally closes the current database connection.
public purge(bool $closeCurrent = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$closeCurrent | bool | If 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(): intReturn Value:
int - Return the number of pooled connections.
The pool is static, so it is shared by all
Connectioninstances.
getOpenConnections
Get the number of currently open driver connections.
public getOpenConnections(): intReturn 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.