Files
blog/app/Model/PostModel.php
2025-06-20 07:55:37 +00:00

118 lines
3.2 KiB
PHP

<?php
namespace Blog\Model;
use Blog\Entity\Post;
use Blog\Database\Database;
use Exception;
class PostModel {
private $db;
public function __construct() {
$this->db = Database::getConnection();
}
/**
* Gibt alle Blogposts als Array von Post-Objekten zurück.
*
* @return Post[] Array mit allen Blogposts.
* @throws Exception Wenn keine Einträge vorhanden sind.
*/
public function getPosts(): array {
$posts = [];
$query = $this->db->query(<<<SQL
SELECT p.id, u.username, p.title, p.content, p.stamp
FROM posts p
JOIN users u ON u.id = p.author_id
ORDER BY p.id DESC
SQL);
if(!$query->rowCount())
throw new Exception("no entries available");
while($row = $query->fetchObject()) {
$posts[] = new Post($row->id, $row->title, $row->content, $row->username, $row->stamp);
}
return $posts;
}
/**
* Gibt einen einzelnen Blogpost anhand der ID zurück.
*
* @param int $id Die ID des Blogposts.
* @return Post|null Das Post-Objekt oder null, falls nicht gefunden.
* @throws Exception Wenn kein Eintrag gefunden wurde.
*/
public function getPost($id): ?Post {
$stmt = $this->db->prepare(<<<SQL
SELECT p.id, u.username, p.title, p.content, p.stamp
FROM posts p
JOIN users u ON u.id = p.author_id
WHERE p.id = :id
LIMIT 1
SQL);
$stmt->bindParam(":id", $id, $this->db::PARAM_INT);
$stmt->execute();
if(!$stmt->rowCount())
throw new Exception("no entry found");
$row = $stmt->fetchObject();
return new Post($row->id, $row->title, $row->content, $row->username, $row->stamp);
}
/**
* Aktualisiert den Inhalt eines Blogposts.
*
* @param int $id Die ID des Blogposts.
* @param string $content Der neue Inhalt.
* @return bool Erfolg der Aktualisierung.
*/
public function updatePostContent($id, $content) {
$stmt = $this->db->prepare(<<<SQL
UPDATE posts
SET content = :content
WHERE id = :id
SQL);
$stmt->bindValue(':content', $content, \PDO::PARAM_STR);
$stmt->bindValue(':id', $id, \PDO::PARAM_INT);
return $stmt->execute();
}
/**
* Legt einen neuen Blogpost an.
*
* @param string $title Der Titel des Blogposts.
* @param string $content Der Inhalt des Blogposts.
* @param int $authorId Die ID des Autors.
* @return bool Erfolg des Einfügens.
*/
public function createPost($title, $content, $authorId) {
$stmt = $this->db->prepare(<<<SQL
INSERT INTO posts (title, content, author_id, stamp)
VALUES
(:title, :content, :author_id, :stamp)
SQL);
$stmt->bindValue(':title', $title, \PDO::PARAM_STR);
$stmt->bindValue(':content', $content, \PDO::PARAM_STR);
$stmt->bindValue(':author_id', $authorId, \PDO::PARAM_INT);
$stmt->bindValue(':stamp', time(), \PDO::PARAM_INT);
return $stmt->execute();
}
/**
* Löscht einen Blogpost anhand der ID.
*
* @param int $id Die ID des Blogposts.
* @return bool Erfolg des Löschens.
*/
public function deletePost($id) {
$stmt = $this->db->prepare(<<<SQL
DELETE FROM posts
WHERE id = :id
SQL);
$stmt->bindValue(':id', $id, \PDO::PARAM_INT);
return $stmt->execute();
}
}