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, fa