Browse Source

Latest, cached

imwald
Nuša Pukšič 3 months ago
parent
commit
4fd561667d
  1. 13
      src/Controller/DefaultController.php

13
src/Controller/DefaultController.php

@ -50,8 +50,12 @@ class DefaultController extends AbstractController
* @throws Exception * @throws Exception
*/ */
#[Route('/latest-articles', name: 'latest_articles')] #[Route('/latest-articles', name: 'latest_articles')]
public function latestArticles(FinderInterface $finder): Response public function latestArticles(FinderInterface $finder, CacheItemPoolInterface $articlesCache): Response
{ {
$cacheKey = 'latest_articles_list';
$cacheItem = $articlesCache->getItem($cacheKey);
if (!$cacheItem->isHit()) {
// Query all articles and sort by created_at descending // Query all articles and sort by created_at descending
$query = new Query(); $query = new Query();
$query->setSize(50); $query->setSize(50);
@ -64,8 +68,13 @@ class DefaultController extends AbstractController
$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', [ return $this->render('pages/latest-articles.html.twig', [
'articles' => $articles, 'articles' => $cacheItem->get(),
]); ]);
} }

Loading…
Cancel
Save