Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always cache the menu #2853

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions config/services_dev.yaml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
services:

# menus
Bolt\Menu\StopwatchBackendMenuBuilder:
Bolt\Menu\CachedBackendMenuBuilder:
decorates: Bolt\Menu\BackendMenuBuilder
autowire: true
Bolt\Menu\BackendMenuBuilderInterface: '@Bolt\Menu\StopwatchBackendMenuBuilder'
Bolt\Menu\BackendMenuBuilderInterface: '@Bolt\Menu\CachedBackendMenuBuilder'

Bolt\Menu\StopwatchFrontendMenuBuilder:
Bolt\Menu\CachedFrontendMenuBuilder:
decorates: Bolt\Menu\FrontendMenuBuilder
autowire: true
Bolt\Menu\FrontendMenuBuilderInterface: '@Bolt\Menu\StopwatchFrontendMenuBuilder'
Bolt\Menu\FrontendMenuBuilderInterface: '@Bolt\Menu\CachedFrontendMenuBuilder'
3 changes: 3 additions & 0 deletions public/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
use Symfony\Component\ErrorHandler\Debug;
use Symfony\Component\HttpFoundation\Request;

set_time_limit(0);
@ini_set('memory_limit', '1024M');

require dirname(__DIR__).'/vendor/autoload.php';

(new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
Expand Down
36 changes: 32 additions & 4 deletions src/Canonical.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;

class Canonical
{
Expand Down Expand Up @@ -43,14 +46,20 @@ class Canonical

/** @var RouterInterface */
private $router;
/** @var Stopwatch */
private $stopwatch;
/** @var TagAwareCacheInterface */
private $cache;

public function __construct(Config $config, UrlGeneratorInterface $urlGenerator, RequestStack $requestStack, RouterInterface $router, string $defaultLocale)
public function __construct(Config $config, UrlGeneratorInterface $urlGenerator, RequestStack $requestStack, RouterInterface $router, string $defaultLocale, Stopwatch $stopwatch, TagAwareCacheInterface $cache)
{
$this->config = $config;
$this->urlGenerator = $urlGenerator;
$this->request = $requestStack->getCurrentRequest() ?? Request::createFromGlobals();
$this->defaultLocale = $defaultLocale;
$this->router = $router;
$this->stopwatch = $stopwatch;
$this->cache = $cache;

$this->init();
}
Expand Down Expand Up @@ -173,7 +182,24 @@ public function setPath(?string $route = null, array $params = []): void
$this->path = $this->generateLink($route, $params, false);
}

public function generateLink(?string $route, ?array $params, $canonical = false): ?string
public function generateLink(?string $route, ?array $params, $canonical = false): string
{
$cacheKey = 'generateLink_' . md5($route . implode('-', $params) . (string) $canonical);

$this->stopwatch->start('bolt.GenerateLink');

$link = $this->cache->get($cacheKey, function (ItemInterface $item) use ($route, $params, $canonical) {
$item->tag('routes');

return $this->generateLinkHelper($route, $params, $canonical);
});

$this->stopwatch->stop('bolt.GenerateLink');

return $link;
}

private function generateLinkHelper(?string $route, ?array $params, $canonical = false): string
{
$removeDefaultLocaleOnCanonical = $this->config->get('general/localization/remove_default_locale_on_canonical', true);
$hasDefaultLocale = isset($params['_locale']) && $params['_locale'] === $this->defaultLocale;
Expand All @@ -197,15 +223,17 @@ public function generateLink(?string $route, ?array $params, $canonical = false)
}

try {
return $this->urlGenerator->generate(
$link = $this->urlGenerator->generate(
$route,
$params,
$canonical ? UrlGeneratorInterface::ABSOLUTE_URL : UrlGeneratorInterface::ABSOLUTE_PATH
);
} catch (InvalidParameterException | MissingMandatoryParametersException | RouteNotFoundException | \TypeError $e) {
// Just use the current URL /shrug
return $canonical ? $this->request->getUri() : $this->request->getPathInfo();
$link = $canonical ? $this->request->getUri() : $this->request->getPathInfo();
}

return $link;
}

private function routeRequiresParam(string $route, string $param): bool
Expand Down
10 changes: 10 additions & 0 deletions src/Entity/Content.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,16 @@ public function getId(): ?int
return $this->id;
}

public function getCacheKey(?string $locale = null): string
{
$key = sprintf('record-%05d', $this->getId());
if ($locale !== null) {
$key .= '-' . $locale;
}

return $key;
}

/**
* @see \Bolt\Event\Listener\ContentFillListener
*/
Expand Down
4 changes: 2 additions & 2 deletions src/Event/Subscriber/ContentSaveSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public function __construct(TagAwareCacheInterface $cache)

public function postSave(ContentEvent $event): ContentEvent
{
// Make sure we flush the cache for the menus
$this->cache->invalidateTags(['backendmenu', 'frontendmenu']);
// Make sure we flush the cache
$this->cache->invalidateTags(['backendmenu', 'frontendmenu', $event->getContent()->getCacheKey(), $event->getContent()->getContentTypeSlug()]);

// Saving an entry in the log.
$context = [
Expand Down
15 changes: 13 additions & 2 deletions src/Menu/CachedBackendMenuBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Bolt\Menu;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
Expand All @@ -20,22 +21,32 @@ final class CachedBackendMenuBuilder implements BackendMenuBuilderInterface
/** @var RequestStack */
private $requestStack;

public function __construct(BackendMenuBuilderInterface $menuBuilder, TagAwareCacheInterface $cache, RequestStack $requestStack)
/** @var Stopwatch */
private $stopwatch;

public function __construct(BackendMenuBuilderInterface $menuBuilder, TagAwareCacheInterface $cache, RequestStack $requestStack, Stopwatch $stopwatch)
{
$this->cache = $cache;
$this->menuBuilder = $menuBuilder;
$this->requestStack = $requestStack;
$this->stopwatch = $stopwatch;
}

public function buildAdminMenu(): array
{
$this->stopwatch->start('bolt.backendMenu');

$locale = $this->requestStack->getCurrentRequest()->getLocale();
$cacheKey = 'backendmenu_' . $locale;

return $this->cache->get($cacheKey, function (ItemInterface $item) {
$menu = $this->cache->get($cacheKey, function (ItemInterface $item) {
$item->tag('backendmenu');

return $this->menuBuilder->buildAdminMenu();
});

$this->stopwatch->stop('bolt.backendMenu');

return $menu;
}
}
15 changes: 13 additions & 2 deletions src/Menu/CachedFrontendMenuBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
use Twig\Environment;
Expand All @@ -21,21 +22,31 @@ final class CachedFrontendMenuBuilder implements FrontendMenuBuilderInterface
/** @var Request */
private $request;

public function __construct(FrontendMenuBuilderInterface $menuBuilder, TagAwareCacheInterface $cache, RequestStack $requestStack)
/** @var Stopwatch */
private $stopwatch;

public function __construct(FrontendMenuBuilderInterface $menuBuilder, TagAwareCacheInterface $cache, RequestStack $requestStack, Stopwatch $stopwatch)
{
$this->cache = $cache;
$this->menuBuilder = $menuBuilder;
$this->request = $requestStack->getCurrentRequest();
$this->stopwatch = $stopwatch;
}

public function buildMenu(Environment $twig, ?string $name = null): array
{
$this->stopwatch->start('bolt.frontendMenu');

$key = 'frontendmenu_' . ($name ?: 'main') . '_' . $this->request->getLocale();

return $this->cache->get($key, function (ItemInterface $item) use ($name, $twig) {
$menu = $this->cache->get($key, function (ItemInterface $item) use ($name, $twig) {
$item->tag('frontendmenu');

return $this->menuBuilder->buildMenu($twig, $name);
});

$this->stopwatch->stop('bolt.frontendMenu');

return $menu;
}
}
31 changes: 0 additions & 31 deletions src/Menu/StopwatchBackendMenuBuilder.php

This file was deleted.

32 changes: 0 additions & 32 deletions src/Menu/StopwatchFrontendMenuBuilder.php

This file was deleted.

55 changes: 43 additions & 12 deletions src/Twig/FieldExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
use Bolt\Utils\ContentHelper;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;
use Tightenco\Collect\Support\Collection;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
Expand All @@ -38,19 +41,26 @@ class FieldExtension extends AbstractExtension

/** @var Query */
private $query;
/** @var Stopwatch */
private $stopwatch;

/** @var TagAwareCacheInterface */
private $cache;

public function __construct(
Notifications $notifications,
ContentRepository $contentRepository,
Config $config,
ContentHelper $contentHelper,
Query $query)
Query $query, Stopwatch $stopwatch, TagAwareCacheInterface $cache)
{
$this->notifications = $notifications;
$this->contentRepository = $contentRepository;
$this->config = $config;
$this->contentHelper = $contentHelper;
$this->query = $query;
$this->stopwatch = $stopwatch;
$this->cache = $cache;
}

/**
Expand Down Expand Up @@ -275,19 +285,40 @@ private function selectOptionsContentType(Field $field): Collection
'order' => $order,
];

/** @var Content[] $records */
$records = iterator_to_array($this->query->getContent($contentTypeSlug, $params)->getCurrentPageResults());
$options = $this->selectOptionsContentTypeCache($contentTypeSlug, $params, $field, $format);

return new Collection($options);
}

private function selectOptionsContentTypeCache(string $contentTypeSlug, array $params, Field $field, string $format)
{
$cacheKey = 'selectOptions_' . md5($contentTypeSlug . implode('-', $params));

$this->stopwatch->start('selectOptions');

$options = $this->cache->get($cacheKey, function (ItemInterface $item) use ($contentTypeSlug, $params, $field, $format) {
$item->tag($contentTypeSlug);

foreach ($records as $record) {
if ($field->getDefinition()->get('mode') === 'format') {
$formattedKey = $this->contentHelper->get($record, $field->getDefinition()->get('format'));
/** @var Content[] $records */
$records = iterator_to_array($this->query->getContent($contentTypeSlug, $params)->getCurrentPageResults());

$options = [];

foreach ($records as $record) {
if ($field->getDefinition()->get('mode') === 'format') {
$formattedKey = $this->contentHelper->get($record, $field->getDefinition()->get('format'));
}
$options[] = [
'key' => $formattedKey ?? $record->getId(),
'value' => $this->contentHelper->get($record, $format),
];
}
$options[] = [
'key' => $formattedKey ?? $record->getId(),
'value' => $this->contentHelper->get($record, $format),
];
}

return new Collection($options);
return $options;
});

$this->stopwatch->stop('selectOptions');

return $options;
}
}
Loading