40 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			40 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
| <?php
 | |
| 
 | |
| namespace App\Core;
 | |
| 
 | |
| use \Exception;
 | |
| use \PDO;
 | |
| use \PDOException;
 | |
| 
 | |
| /**
 | |
|  * Encapsulates a single connection to a database.
 | |
|  * TODO: add different driver implementations.
 | |
|  */
 | |
| class Database
 | |
| {
 | |
|     public PDO $conn;
 | |
| 
 | |
|     public function __construct(array $config)
 | |
|     {
 | |
|         if ($config['name'] !== 'mysql')
 | |
|         {
 | |
|             throw new Exception("Database error: ".$config['name']." is not implemented");
 | |
|         }
 | |
| 
 | |
|         try {
 | |
|             $this->conn = $this->connectWithMySQL($config['args']);
 | |
|         } catch (PDOException $e) {
 | |
|             throw new PDOException("Database error: " . $e->getMessage());
 | |
|         }
 | |
|     }
 | |
| 
 | |
|     private function connectWithMySQL(array $args): object 
 | |
|     {
 | |
|         $dsn = "mysql:host={$args['host']};dbname={$args['database']};charset={$args['charset']}";
 | |
|         $options = [
 | |
|             PDO::ATTR_PERSISTENT => true,
 | |
|             PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION // in PHP 8 and above, this will be the default mode.
 | |
|         ];
 | |
|         return new PDO($dsn, $args['user'], $args['password'], $options);
 | |
|     }
 | |
| } |