statt txt -> json

This commit is contained in:
NOrtmann1
2026-05-27 16:03:56 +02:00
parent f2a9d8d1b3
commit 890187cff2
4 changed files with 120 additions and 37 deletions
+37 -31
View File
@@ -1,15 +1,18 @@
<?php
require_once 'ArticleManagerDAO.php';
require_once $abs_path . 'ArticleManagerDAO.php';
/**
* Klasse: Eine lokale Lösung der DatenbankDAO.
* schreibt zunächst Daten lokal in das Verzeichnis und kann diese wieder auslesen.
* Klasse: Eine lokale Lösung des ArticleManagerDAO.
* Schreibt zunächst Daten lokal in das Verzeichnis und kann diese wieder auslesen.
*
* @author Niklas Ortmann
*/
class ArticleManager implements ArticleManagerDAO {
private string $file = $abs_path . "data/articles.json";
/**
* Gibt die Datenbank-Instanz zurück.
* Gibt die ArticleManager-Instanz zurück.
* @return ArticleManager
*/
public static function getInstance()
{
@@ -20,38 +23,34 @@ class ArticleManager implements ArticleManagerDAO {
return self::$instance;
}
/**
* Prüft, ob die lokalen txt-Dateien existieren.
* Wenn nicht, werden diese erstellt.
* Speichert alle Artikel/Beiträge in der Datei.
* @param $articles
* @return void
*/
public function __construct()
public function saveArticle($articles)
{
file_put_contents(
$this->file,
json_encode($articles, JSON_PRETTY_PRINT)
);
}
public function newArticle($article) {
$newData = array(
"title" => $article->getTitle(),
"content" => $article->getContent(),
"author" => $article->getAuthor(),
"category" => $article->getCategory(),
//"tags" => $article->getTags(), TODO: Später hinzufügen
"date" => date("d.m.Y, H:i")
);
$newData = base64_encode(serialize($newData));
if (!file_exists("articles.txt")) {
$newData = fopen("articles.txt", "xb");
fclose($newData);
}
$previousData = file_get_contents("articles.txt");
if (file_put_contents("articles.txt", "$newData\n$previousData")) {
// TODO: Vernünftige Rückmeldung implementieren.
echo "Artikel erfolgreich gespeichert!";
} else {
// TODO: passende Exceptions werfen.
echo "Fehler!";
}
public function addArticle($title, $content, $author, $category, array $tags)
{
$articles = $this->getAllArticles();
$articles[] = [
"id" => count($articles)+1,
"title" => $title,
"content" => $content,
"author" => $author,
"category" => $category,
"tags" => $tags
];
$this->saveArticle($articles);
}
public function updateArticle($id, $title, $content, $author)
@@ -71,7 +70,14 @@ class ArticleManager implements ArticleManagerDAO {
public function getAllArticles()
{
// TODO: Implement getAllArticles() method.
if (!file_exists($this->file)) {
return [];
}
$json = file_get_contents($this->file);
$articles = json_decode($json, true);
return is_array($articles) ? $articles : [];
}
}