getConnection(); $db->exec(" CREATE TABLE IF NOT EXISTS comments ( id INTEGER PRIMARY KEY AUTOINCREMENT, article_id INTEGER NOT NULL, author TEXT NOT NULL, content TEXT NOT NULL, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); "); unset($db); } catch (PDOException $e) { throw new RuntimeException( "Kommentardatenbank konnte nicht erstellt werden." ); } } /** * Baut die Verbindung zur SQLite-Datenbank auf. * * @return PDO Datenbankverbindung */ private function getConnection() { try { $dsn = 'sqlite:' . __DIR__ . '/../../db/comments.db'; $db = new PDO($dsn, null, null); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $db; } catch (PDOException $e) { throw new RuntimeException( "Verbindung zur Kommentardatenbank fehlgeschlagen." ); } } /** * Gibt die Singleton-Instanz zurück. * * @return DatabaseCommentManager */ public static function getInstance() { if (self::$instance === null) { self::$instance = new DatabaseCommentManager(); } return self::$instance; } /** * Speichert einen neuen Kommentar * zu einem Beitrag. * * @param int $articleId ID des Beitrags * @param string $author Autor des Kommentars * @param string $content Inhalt des Kommentars * * @return void */ public function addComment( $articleId, $author, $content ) { try { $db = $this->getConnection(); $sql = " INSERT INTO comments ( article_id, author, content ) VALUES ( :articleId, :author, :content ) "; $command = $db->prepare($sql); $command->execute([ ":articleId" => $articleId, ":author" => $author, ":content" => $content ]); } catch (PDOException $e) { throw new RuntimeException( "Kommentar konnte nicht gespeichert werden." ); } } /** * Lädt alle Kommentare eines Beitrags. * * @param int $articleId ID des Beitrags * * @return Comment[] */ public function getCommentsByArticle( $articleId ) { try { $db = $this->getConnection(); $sql = " SELECT * FROM comments WHERE article_id = :articleId ORDER BY created DESC "; $command = $db->prepare($sql); $command->execute([ ":articleId" => $articleId ]); $comments = []; while ($row = $command->fetch(PDO::FETCH_ASSOC)) { $comments[] = new Comment( $row["id"], $row["article_id"], $row["author"], $row["content"], $row["created"] ); } return $comments; } catch (PDOException $e) { throw new RuntimeException( "Kommentare konnten nicht geladen werden." ); } } }