setDatabase($database); $this->connect(); } protected Database $database; public function setDatabase(Database $database): ConnectionInterface { $this->database = $database; return $this; } public function getDatabase(): Database { return $this->database; } public function connect(): ConnectionInterface { if (!isset($this->pdo)) { if ($this->getDatabase()->needsUser()) { $pdo = new PDO($this->getDatabase()->getDSN(), $this->getDatabase()->getUsername(), $this->getDatabase()->getPassword()); } else { $pdo = new PDO($this->getDatabase()->getDSN()); } $this->setPDO($pdo); } return $this; } protected PDO $pdo; public function setPDO(PDO $pdo): ConnectionInterface { $this->pdo = $pdo; return $this; } public function getPDO(): PDO { return $this->pdo; } public function query(string $query): ResultSetInterface { $st = $this->getPDO()->query($query); if (!$st) { throw new PDOException("Could not run query {$query}"); } return new ResultSet($st); } public function prepare(string $query): ResultSetInterface { $st = $this->getPDO()->prepare($query); if (!$st) { throw new PDOException("Could not prepare query {$query}"); } return new ResultSet($st); } public function execute(string $query, array $values): ResultSetInterface { return $this->prepare($query)->execute($values); } public function transaction(): TransactionInterface { return new Transaction($this->getPDO()); } }