If your preprocess doesn't affect the result of the page, and needs to execute even when the page is served from the page cache, you should move your logic to a Kernel Event subscriber, which replaces hook_boot()
and hook_exit()
from Drupal 7.
DrupalizeMe has an article on Event Subscribers, but the basic components are creating a class that implements EventSubscriberInterface
, and then registering it as a service.
MYMODULE/EventSubscriber/MyEventSubscriber.php
class MyEventSubscriber implements EventSubscriberInterface {
static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = ['onResponse'];
return $events;
}
public function onResponse(FilterResponseEvent $event) {
$request = $event->getRequest();
$response = $event->getResponse();
$parameter_value = $request->query->get('parameter_name');
$response->headers->setCookie(new Cookie('cookie_name', 'cookie_value'));
}
}
MYMODULE/MYMODULE.services.yml
MYMODULE.my_event_subscriber:
class: Drupal\MYMODULE\EventSubscriber\MyEventSubscriber
arguments: []
tags:
- { name: event_subscriber }
The request event can modify the request before other components receive it, but cannot affect the response. The response event cannot modify the request, but is able to alter the response after it has been composed.
If you need to do both, your service object can store some state during the request event, and then alter the response based on that state during the response event.