TrishulApi\Core\Data\DB

Namespace: TrishulApi\Core\Data
Author: Shyam Dubey
Since: v1.0.0

Overview

The DB class is responsible for providing a database connection object in the Trishul API framework. It reads configuration from environment variables and supports multiple database types (MySQL, PostgreSQL, Oracle). The class ensures a singleton connection and throws exceptions if configuration is missing or connection fails.

Usage Example


use TrishulApi\Core\Data\DB;

try {
    // Get PDO connection
    $pdo = DB::get_connection();

    // Use PDO as usual
    $stmt = $pdo->query('SELECT * FROM users');
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Handle connection errors
    echo "Database error: " . $e->getMessage();
}
        

Environment Variables

The following environment variables must be set for the database connection:

VariableDescription
DB_HOSTDatabase server hostname or IP address
DB_PORTDatabase server port
DB_TYPEDatabase type (mysql, postgres, oracle)
DB_USERNAMEDatabase username
DB_PASSWORDDatabase password
DB_NAMEDatabase name
Note: If any of these variables are missing, an exception will be thrown.

Methods

public function __construct()

Initializes the database configuration from environment variables. Throws an exception if configuration is incomplete. Usually, you do not need to instantiate this class directly; use get_connection() instead.

public static function get_connection(): PDO

Returns a singleton PDO connection object. If the connection does not exist, it is created using the configuration from environment variables. Supports MySQL, PostgreSQL, and Oracle.

Supported Database Types

Notes

Related Classes

Changelog