38 lines
		
	
	
		
			946 B
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			38 lines
		
	
	
		
			946 B
		
	
	
	
		
			PHP
		
	
	
	
	
	
<?php
 | 
						|
 | 
						|
namespace App\Core;
 | 
						|
 | 
						|
use \InvalidArgumentException;
 | 
						|
use \PDO;
 | 
						|
use \PDOException;
 | 
						|
 | 
						|
/**
 | 
						|
 * Encapsulates a single connection to a database.
 | 
						|
 */
 | 
						|
class Database
 | 
						|
{
 | 
						|
    public PDO $conn;
 | 
						|
 | 
						|
    public function __construct(array $config)
 | 
						|
    {
 | 
						|
        if ($config['name'] !== 'mysql')
 | 
						|
        {
 | 
						|
            throw new InvalidArgumentException("Database error: driver ".$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,
 | 
						|
        ];
 | 
						|
        return new PDO($dsn, $args['user'], $args['password'], $options);
 | 
						|
    }
 | 
						|
} |