Example #1
0
 /**
  * AbstractPdo constructor.
  *
  * @param string $dsn
  * @param string|null $user
  * @param string|null $pass
  * @param array $options
  * @throws DatabaseException
  */
 public function __construct(string $dsn, string $user = null, string $pass = null, array $options)
 {
     try {
         $this->pdo = new \PDO($dsn, $user, $pass, $options);
     } catch (\PDOException $e) {
         throw DatabaseException::connectionError($e->getMessage());
     }
 }
Example #2
0
 /**
  * Database constructor.
  *
  * Establish a new connection with a database using PDO
  *
  * @param string $driver
  * @param string $dbName
  * @param string $host
  * @param string|null $user
  * @param string|null $pass
  * @param bool $persistent
  * @throws DatabaseException
  */
 public function __construct(string $driver, string $dbName, string $host = "localhost", string $user = null, string $pass = null, bool $persistent = false)
 {
     $this->config = new Config();
     $this->queryBuilder = new QueryBuilder();
     $this->lastQuery = new LastQuery();
     $this->errors = [];
     // Check if PDO extension is loaded, we need PDO
     if (!extension_loaded("pdo")) {
         throw DatabaseException::connectionError("PDO extension is not loaded with PHP");
     }
     // Check if driver is available
     if (!in_array($driver, \PDO::getAvailableDrivers())) {
         throw DatabaseException::connectionError(sprintf('Passed driver "%1$s" is not an available PDO driver', $driver));
     }
     // Generate DSN
     if ($driver === "sqlite") {
         // SQLite dsn
         $dsn = "sqlite:" . $dbName;
     } else {
         // Split host argument in actual hostname and port
         $host = explode(":", $host);
         $port = $host[1] ?? null;
         $dbHost = $host[0];
         $dbPort = isset($port) ? sprintf(";port=%d", $port) : "";
         // Generate DSN
         $dsn = sprintf("%s:host=%s%s;dbname=%s;charset=utf8mb4", $driver, $dbHost, $dbPort, $dbName);
     }
     // PDO connection options
     $options = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
     if ($persistent === true) {
         $options[\PDO::ATTR_PERSISTENT] = true;
         $this->config->persistent = true;
     }
     // Connect to PDO via AbstractPdo adapter
     parent::__construct($dsn, $user, $pass, $options);
     $this->config->driver = $driver;
 }