Drupal Answers Asked by user34185 on December 8, 2021
I am trying to implement a KernelEvents::REQUEST event subscriber to perform some action on page load.
I need this event to fire regardless of whether the requested page exists in the Drupal cache – it seems that KernelEvents::REQUEST does not fire when Drupal serves something from the cache.
Is there an event I can use to achieve this, or must I implement my requirements as some form of middleware?
Drupal 8 has two level cache, page cache and dynamic page cache.
Yes you can intercept the dynamic page cache as what @4k4 mentioned. The issue you are having is more likely to intercept the page cache. The key is in here.
There are a few solutions for this:
Add new class which implements 'HttpKernelInterface' and register 'http_middleware' with higher priority than 200 (280 will do). See 'PageCache' class and implementations for references.
Create new class to alter the existing 'PageCache' by extending from 'ServiceProviderBase'. Check this out for references here. Then, create new class to extends the 'PageCache'.
Here is code references:
This is StaticCacheServiceProvider.php:
/**
* Modifies the language manager service.
*/
class StaticCacheServiceProvider extends ServiceProviderBase
{
/**
* {@inheritdoc}
*/
public function alter(ContainerBuilder $container)
{
// Overrides language_manager class to test domain language negotiation.
$definition = $container->getDefinition('http_middleware.page_cache');
$definition->setClass('Drupalyour_moduleStackMiddlewareStaticCache');
}
}
This is StaticCache.php:
/**
* Executes the page caching before the main kernel takes over the request.
*/
class StaticCache extends PageCache
{
/**
* {@inheritdoc}
*/
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
// do special logic here.
$response = parent::handle($request, $type, $catch);
return $response;
}
}
Hope helps.
Answered by kororo on December 8, 2021
The dynamic cache subscribes an event with priority 27. If you want that your code runs before that you have to use a priority >27:
public static function getSubscribedEvents() {
$events = [];
// Run after AuthenticationSubscriber (necessary for the 'user' cache
// context; priority 300) and MaintenanceModeSubscriber (Dynamic Page Cache
// should not be polluted by maintenance mode-specific behavior; priority
// 30), but before ContentControllerSubscriber (updates _controller, but
// that is a no-op when Dynamic Page Cache runs; priority 25).
$events[KernelEvents::REQUEST][] = ['onRequest', 27];
Which runs DynamicPageCacheSubscriber::onRequest..
Answered by 4k4 on December 8, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP