deadjournal/controllers/PostController.php
2025-01-08 22:46:44 +05:00

106 lines
2.6 KiB
PHP
Executable File

<?php
namespace Controllers;
use Core\Controller;
use Models\PostModel;
use Models\TagModel;
class PostController extends Controller
{
private $postModel;
private $tagModel;
public function __construct()
{
parent::__construct();
$this->postModel = new PostModel();
$this->tagModel = new TagModel();
}
public function index()
{
$postsPerPage = $postsPerPage = MAX_POSTS_PER_PAGE;
if ($postsPerPage < 1) {
$postsPerPage = 5; // fallback
}
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) {
$page = 1;
}
$totalPosts = $this->postModel->countAll();
$totalPages = ceil($totalPosts / $postsPerPage);
if ($totalPages < 1) {
$totalPages = 1;
}
$offset = ($page - 1) * $postsPerPage;
$posts = $this->postModel->getPaginated($offset, $postsPerPage);
foreach ($posts as &$post) {
// getTagsByPostId() returns all tags for this post
$post['tags'] = $this->tagModel->getTagsByPostId($post['id']);
}
$this->view->render('post/list.php', [
'posts' => $posts,
'totalPages' => $totalPages,
'currentPage' => $page
]);
}
public function view($id)
{
// Просмотр конкретного поста
$post = $this->postModel->getById($id);
if (!$post) {
die("Пост не найден");
}
$tags = $this->tagModel->getTagsByPostId($id);
$this->view->render('post/view.php', [
'post' => $post,
'tags' => $tags
]);
}
public function tag($tagName)
{
// Посты по тегу
$posts = $this->tagModel->getPostsByTagName($tagName);
// Attach each post's tags
foreach ($posts as &$post) {
$post['tags'] = $this->tagModel->getTagsByPostId($post['id']);
}
// Pass them to the list view
$this->view->render('post/list.php', [
'posts' => $posts,
'tagName' => $tagName
]);
}
public function archive($yearMonth)
{
list($year, $month) = explode('-', $yearMonth);
$posts = $this->postModel->getByYearMonth($year, $month);
$monthName = date('F', mktime(0, 0, 0, (int)$month, 1, (int)$year));
$archiveLabel = $monthName . ' ' . $year;
$this->view->render('post/list.php', [
'posts' => $posts,
'archiveLabel' => $archiveLabel
]);
}
}