70 lines
1.8 KiB
PHP
70 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
class PostManager
|
|
{
|
|
private PDO $db;
|
|
|
|
public function __construct(PDO $db)
|
|
{
|
|
$this->db = $db;
|
|
}
|
|
|
|
public function getAll(): array
|
|
{
|
|
$stmt = $this->db->query('SELECT * FROM posts ORDER BY created_at DESC');
|
|
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
public function get(int $id): ?array
|
|
{
|
|
$stmt = $this->db->prepare('SELECT * FROM posts WHERE id = :id');
|
|
$stmt->execute(['id' => $id]);
|
|
$post = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
return $post ?: null;
|
|
}
|
|
|
|
public function create(string $title, string $content, string $published_at): int
|
|
{
|
|
$stmt = $this->db->prepare('
|
|
INSERT INTO posts (title, content, created_at, is_published)
|
|
VALUES (:title, :content, :published_at, true)
|
|
');
|
|
$stmt->execute([
|
|
'title' => $title,
|
|
'content' => $content,
|
|
'published_at' => $published_at,
|
|
]);
|
|
return (int)$this->db->lastInsertId();
|
|
}
|
|
|
|
|
|
public function update(int $id, string $title, string $content, string $published_at, bool $published): bool
|
|
{
|
|
$stmt = $this->db->prepare('
|
|
UPDATE posts
|
|
SET title = :title,
|
|
content = :content,
|
|
created_at = :published_at,
|
|
is_published = :published,
|
|
updated_at = NOW()
|
|
WHERE id = :id
|
|
');
|
|
return $stmt->execute([
|
|
'id' => $id,
|
|
'title' => $title,
|
|
'content' => $content,
|
|
'published_at' => $published_at,
|
|
'published' => $published,
|
|
]);
|
|
}
|
|
|
|
|
|
public function delete(int $id): bool
|
|
{
|
|
$stmt = $this->db->prepare('DELETE FROM posts WHERE id = :id');
|
|
return $stmt->execute(['id' => $id]);
|
|
}
|
|
}
|