From a3e8f03cf1483bb93712dcf5848d466883071193 Mon Sep 17 00:00:00 2001 From: Oliver Davies Date: Mon, 11 Jan 2021 02:20:17 +0000 Subject: [PATCH] Cache the block, not the render array References #3 --- .../blog/src/Plugin/Block/RelatedPostsBlock.php | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/web/modules/custom/blog/src/Plugin/Block/RelatedPostsBlock.php b/web/modules/custom/blog/src/Plugin/Block/RelatedPostsBlock.php index 8fafbe2..c7f9141 100644 --- a/web/modules/custom/blog/src/Plugin/Block/RelatedPostsBlock.php +++ b/web/modules/custom/blog/src/Plugin/Block/RelatedPostsBlock.php @@ -3,6 +3,7 @@ namespace Drupal\opdavies_blog\Plugin\Block; use Drupal\Core\Block\BlockBase; +use Drupal\Core\Cache\Cache; use Drupal\Core\Link; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\Core\Routing\CurrentRouteMatch; @@ -64,10 +65,6 @@ class RelatedPostsBlock extends BlockBase implements ContainerFactoryPluginInter } $build['content'] = [ - '#cache' => [ - 'max-age' => 604800, - 'tags' => ["node:{$currentPost->id()}"], - ], '#items' => $relatedPosts ->sortByDesc(fn(Post $post) => $post->getCreatedTime()) ->map(fn(Post $post) => $this->generateLinkToPost($post)) @@ -79,6 +76,17 @@ class RelatedPostsBlock extends BlockBase implements ContainerFactoryPluginInter return $build; } + public function getCacheMaxAge(): int { + return 604800; + } + + public function getCacheTags(): array { + /** @var Post $post */ + $post = $this->currentRouteMatch->getParameter('node'); + + return Cache::mergeTags(parent::getCacheTags(), ["node:{$post->id()}"]); + } + private function generateLinkToPost(Post $post): Link { return Link::createFromRoute( $post->getTitle(),