|
5 | 5 | namespace imperazim\db; |
6 | 6 |
|
7 | 7 | use imperazim\db\exception\DatabaseException; |
8 | | -use Exception; |
9 | 8 |
|
10 | 9 | /** |
11 | | -* Factory for creating database connections. |
12 | | -* |
13 | | -* Usage: |
14 | | -* $db = DBManager::connect('sqlite', ['database' => '/path/to/mydb']); |
15 | | -* $db = DBManager::connect('mysql', [ |
16 | | -* 'host' => 'localhost', |
17 | | -* 'username' => 'root', |
18 | | -* 'password' => '', |
19 | | -* 'database' => 'mydb' |
20 | | -* ]); |
| 10 | +* Class DBManager |
| 11 | +* @package imperazim\db |
21 | 12 | */ |
22 | 13 | final class DBManager { |
23 | 14 |
|
24 | | - /** |
25 | | - * Connects to the specified database. |
26 | | - * |
27 | | - * @param string $type Database type: 'mysql' or 'sqlite' |
28 | | - * @param array $config Connection configuration |
29 | | - * @return Database Database instance |
30 | | - * @throws DatabaseException If connection fails or type unsupported |
31 | | - */ |
32 | | - public static function connect(string $type, array $config): Database { |
33 | | - try { |
34 | | - return match (strtolower($type)) { |
35 | | - 'mysql' => Mysql::connect( |
36 | | - $config['host'], |
37 | | - $config['username'], |
38 | | - $config['password'], |
39 | | - $config['database'] |
40 | | - ), |
41 | | - 'sqlite' => new Sqlite3( |
42 | | - dirname($config['database']), |
43 | | - pathinfo($config['database'], PATHINFO_FILENAME) |
44 | | - ), |
45 | | - default => throw new DatabaseException("Unsupported database type: $type"), |
46 | | - }; |
47 | | - } catch (DatabaseException $e) { |
48 | | - throw $e; |
49 | | - } catch (Exception $e) { |
50 | | - throw new DatabaseException("Failed to connect to the database: " . $e->getMessage(), 0, $e); |
51 | | - } |
| 15 | + /** |
| 16 | + * Connects to the specified database using the provided configuration. |
| 17 | + * @param string $type The type of database (e.g., 'mysql', 'sqlite'). |
| 18 | + * @param array $config The configuration array for the database connection. |
| 19 | + * @return mixed The database instance. |
| 20 | + * @throws DatabaseException If the connection fails or the configuration is invalid. |
| 21 | + */ |
| 22 | + public static function connect(string $type, array $config): mixed { |
| 23 | + try { |
| 24 | + switch (strtolower($type)) { |
| 25 | + case 'mysql': |
| 26 | + return Mysql::connect($config['host'], $config['username'], $config['password'], $config['database']); |
| 27 | + case 'sqlite': |
| 28 | + $directory = dirname($config['database']); |
| 29 | + $fileName = pathinfo($config['database'], PATHINFO_FILENAME); |
| 30 | + return new Sqlite3($directory, $fileName); |
| 31 | + default: |
| 32 | + throw new DatabaseException("Unsupported database type: $type"); |
| 33 | + } |
| 34 | + } catch (\Exception $e) { |
| 35 | + throw new DatabaseException("Failed to connect to the database: " . $e->getMessage(), 0, $e); |
52 | 36 | } |
| 37 | + } |
53 | 38 | } |
0 commit comments