From 4fd561667d9e65db1daf2d658565ccc20483ffd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nu=C5=A1a=20Puk=C5=A1i=C4=8D?= Date: Tue, 7 Oct 2025 19:29:52 +0200 Subject: [PATCH] Latest, cached --- src/Controller/DefaultController.php | 31 ++++++++++++++++++---------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/Controller/DefaultController.php b/src/Controller/DefaultController.php index 9ef582e..33ec68e 100644 --- a/src/Controller/DefaultController.php +++ b/src/Controller/DefaultController.php @@ -50,22 +50,31 @@ class DefaultController extends AbstractController * @throws Exception */ #[Route('/latest-articles', name: 'latest_articles')] - public function latestArticles(FinderInterface $finder): Response + public function latestArticles(FinderInterface $finder, CacheItemPoolInterface $articlesCache): Response { - // Query all articles and sort by created_at descending - $query = new Query(); - $query->setSize(50); - $query->setSort(['createdAt' => ['order' => 'desc']]); + $cacheKey = 'latest_articles_list'; + $cacheItem = $articlesCache->getItem($cacheKey); + + if (!$cacheItem->isHit()) { + // Query all articles and sort by created_at descending + $query = new Query(); + $query->setSize(50); + $query->setSort(['createdAt' => ['order' => 'desc']]); - // Use collapse to deduplicate by slug field - $collapse = new Collapse(); - $collapse->setFieldname('slug'); - $query->setCollapse($collapse); + // Use collapse to deduplicate by slug field + $collapse = new Collapse(); + $collapse->setFieldname('slug'); + $query->setCollapse($collapse); - $articles = $finder->find($query); + $articles = $finder->find($query); + + $cacheItem->set($articles); + $cacheItem->expiresAfter(300); // Cache for 5 minutes + $articlesCache->save($cacheItem); + } return $this->render('pages/latest-articles.html.twig', [ - 'articles' => $articles, + 'articles' => $cacheItem->get(), ]); }