“Learn how to enhance Drupal 9 performance by disabling cache for specific controller routes, accompanied by detailed example code explanations.”
Example Code:
Define the Route:
my_module.routing.yml my_module.route_name: path: '/custom/route' defaults: _controller: '\Drupal\my_module\Controller\MyController::myMethod' _title: 'Custom Route' requirements: _permission: 'access content'Disable Cache for the Route:
my_module.services.yml services: my_module.route_subscriber: class: '\Drupal\my_module\Routing\RouteSubscriber' tags: - { name: 'event_subscriber' }Implement RouteSubscriber:
MyModule\Routing\RouteSubscriber.php namespace Drupal\my_module\Routing; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\DependencyInjection\ServiceProviderBase; use Symfony\Component\DependencyInjection\Reference; /** * Modifies the language manager service. */ class RouteSubscriber extends ServiceProviderBase { /** * {@inheritdoc} */ public function alter(ContainerBuilder $container) { // Overrides the default DynamicPageCache service for the specified route. $definition = $container->getDefinition('dynamic_page_cache.subscriber'); $definition->setClass('Drupal\my_module\Routing\DynamicPageCacheSubscriber'); } }Create DynamicPageCacheSubscriber:
MyModule\Routing\DynamicPageCacheSubscriber.php namespace Drupal\my_module\Routing; use Drupal\dynamic_page_cache\EventSubscriber\DynamicPageCacheSubscriber as BaseSubscriber; use Symfony\Component\HttpKernel\KernelEvents; /** * Listens to the dynamic_page_cache.response event and disables caching for specific routes. */ class DynamicPageCacheSubscriber extends BaseSubscriber { /** * {@inheritdoc} */ protected $priority = 100; /** * {@inheritdoc} */ public static function getSubscribedEvents() { $events[KernelEvents::RESPONSE][] = ['onResponse', 100]; return $events; } /** * {@inheritdoc} */ public function onResponse($event) { $request = $event->getRequest(); // Disable cache for the specified route. if ($request->attributes->get('_route') == 'my_module.route_name') { $event->getResponse()->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate'); } } }
By following these steps, you can selectively disable caching for specific controller routes in Drupal 9, optimizing your website's performance.
